Java/JSP/Basics

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Advanced Dynamic Web Content Generation. 1

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



Comments in JSP page

   <source lang="java">

<html>

 <HEAD>
   <TITLE>Comments in a JSP</TITLE>
 </HEAD>
 <BODY>
   <% // A Java comment inside a scriptlet - copied into the generated servlet %>
   The exemplar that generated this page uses a combination of HTML, Java and JSP comments.
   <%-- A JSP comment - not copied to the servlet, or the output --%>
 </BODY>

</HTML>

      </source>
   
  
 
  



CSS, JavaScript, VBScript, and JSP 1

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



CSS, JavaScript, VBScript, and JSP 2

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



Declaration Tag Example

   <source lang="java">

<%!

 String name = "Mark";
 String date = "28th April, 2004";

%> <HTML>

 <TITLE>Declaration Tag Example</TITLE>
 <BODY>
   This page was last modified on <%= date %> by <%= name %>.
 </BODY>

</HTML>

      </source>
   
  
 
  



Declaration Tag - Methods

   <source lang="java">

<%!

 private String getName()
 {
   return "Rosy";
 }
 private int getAge()
 {
   return 6;
 }

%> <HTML>

 <HEAD><TITLE>Declaration Tag - Methods</TITLE></HEAD>
 <%= getName() %>, age <%= getAge() %>, is one funny kid!
 

</HTML>


      </source>
   
  
 
  



Embedding Code

   <source lang="java">

<%!

 String[] names = {"Green", "White", "Black", "Red"};

%> <HTML>

 <HEAD><TITLE>Embedding Code</TITLE></HEAD>
 <BODY>

List of people

     <% for (int i=0; i<names.length; i++) { %>
     <% } %>
Name
<%= names[i]%>
 </BODY>

</HTML>


      </source>
   
  
 
  



Expression Language Examples

   <source lang="java">

<html> <head> <title> <html> <head> <title>Expression Language Examples</title> <%

 // set up a page context parameter for use later in the page
 // normally this would have been set within the context of
 // an application
 pageContext.setAttribute("pageColor", "blue");

%> </head> <body bgcolor="${pageScope.pageColor}">

Welcome to the ${param.department} Department

Here are some basic comparisons:

Is 1 less than 2? ${1<2}
Does 5 equal 5? ${5==5}
Is 6 greater than 7? ${6 gt 7}
<p>Now for some math:
6 + 7 = ${6+7}
8 x 9 = ${8*9}


You appear to be using the following browser:

${header["user-agent"]} </body> </html></title>

      </source>
   
  
 
  



JSP Basics ch02

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Basics: Dynamic Page Creation for Data Presentation 2

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /

<html> <head> <link rel=stylesheet type="text/css" href="portal.css"> <title>Select Your Portal</title></head> <body>

Wrox JSP Portal Selector

 

<form action="showportal.jsp" method="get">

Portal Selection

<select name="portchoice"> <option>news</option> <option>weather</option> <option>entertainment</option> </select>

 

<input type="submit" value="Select"/>

</form>

</body> </html> //showportal.jsp <%@ taglib prefix="c" uri="http://java.sun.ru/jsp/jstl/core" %> <html>

<c:choose>
   <c:when test="${param.portchoice == "news"}">
     <jsp:include page="news.jsp" />
   </c:when>
   <c:when test="${param.portchoice == "weather"}">
     <jsp:include page="weather.jsp" />
   </c:when>
   <c:when test="${param.portchoice == "entertainment"}">
     <jsp:include page="entertain.jsp" />
   </c:when>
   <c:otherwise>
      <head><title>System Portal</title></head>
      <body>

Application logic problem detected!

   </c:otherwise>

</c:choose> </body> </html>

//news.jsp <head> <link rel=stylesheet type="text/css" href="portal.css"> <title>News Portal</title> </head> <body>

Welcome to the News Portal!

<jsp:useBean id="newsfeed" class="com.wrox.begjsp.ch2.NewsFeed" scope="request" > <jsp:setProperty name="newsfeed" property="topic" value="news"/> <jsp:getProperty name="newsfeed" property="value"/> </jsp:useBean> <jsp:include page="dummytext.html" />

      </source>
   
  
 
  



JSP Basics: Generalized Templating and Server Scripting 1

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Basics: Generalized Templating and Server Scripting 2

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Basics: Generalized Templating and Server Scripting 3

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Best Practices and Tools

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /
      </source>
   
  
 
  



JSP Directives

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Directives: your page

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Expression Language

   <source lang="java">

<%-- <%@page isScriptingEnabled="true" %> --%> <html> <head> <title>Using the JSP Expression Language</title> </head> <body>

The Expression Language

The value of the name is ${header.userAgent}.

</body> </html>


      </source>
   
  
 
  



JSP: expression language 2

JSP Initialization

   <source lang="java">

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.ru/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet>

 <servlet-name>InitializationJSP</servlet-name>
 <jsp-file>/initialization.jsp</jsp-file>
 <init-param>
   <param-name>testParam</param-name>
   <param-value>hello from web.xml</param-value>
 </init-param>

</servlet> <servlet-mapping>

 <servlet-name>InitializationJSP</servlet-name>
 <url-pattern>/Initialization</url-pattern>

</servlet-mapping> </web-app> //File:initialization.jsp <html> <head> <title>Initialization Parameters and JSP</title> </head> <body> This page has retrieved the following initialization parameter from web.xml:
<%= pageContext.getServletConfig().getInitParameter("testParam") %> </body> </html>


      </source>
   
  
 
  



JSP in J2EE

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



JSP Model 2

JSP Passing Parameters

JSP Performance

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /
      </source>
   
  
 
  



JSP post

   <source lang="java">

//jspPost.jsp /* <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <c:set var="mapParams" value="${param}" /> <jsp:useBean id="postBean" class="com.jexp.PostBean" > <jsp:setProperty name="parameters" value="${mapParams}" /> <jsp:setProperty name="url" value="http://localhost:8080/home/viewPost.jsp" /> </jsp:useBean> <jsp:getProperty id="postBean" property="post"/>

  • /

//viewPost.jsp /* <%@page contentType="text/html"%><%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html> <head><title>Post Data Viewer</title></head> <body>

Here is your posted data

<c:forEach var="map_entry" items="${param}">

   <c:out value="${map_entry.key}" />: 
 <c:out value="${map_entry.value}" />

</c:forEach> </body> </html>

  • /

package com.jexp; import java.util.Map; import java.util.Iterator; import java.util.Map.Entry; import org.apache.rumons.httpclient.HttpClient; import org.apache.rumons.httpclient.HttpStatus; import org.apache.rumons.httpclient.methods.PostMethod; import org.apache.rumons.httpclient.NameValuePair; import org.apache.rumons.httpclient.HttpException; public class PostBean implements java.io.Serializable { private Map parameters; private String url; public PostBean(){ } public void setParameters(Map param){

 if (param != null)
     parameters = param;

} public Map getParameters(){

   return parameters;
   }
   

public void setUrl(String url){

 if (url != null && !(url.equals("")))
     this.url=url;

} public String getUrl(){

   return url;
   }
 

public String getPost() throws java.io.IOException,HttpException{

   if (url == null || url.equals("") || parameters == null)
       throw new IllegalStateException("Invalid url or parameters in PostBean.getPost method.");
   String returnData = "";
   HttpClient httpClient = new HttpClient();
   PostMethod postMethod = new PostMethod(url);
   //convert the Map passed into the bean to a NameValuePair[] type
   NameValuePair[] postData = getParams(parameters);  
   //the 2.0 beta1 version has a
  //PostMethod.setRequestBody(NameValuePair[])
   //method, as addParameters is deprecated
   postMethod.addParameters(postData);
   httpClient.executeMethod(postMethod);
    //A "200 OK" HTTP Status Code
   if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
       returnData= postMethod.getResponseBodyAsString();
   } else {
       returnData= "The POST action raised an error: " + postMethod.getStatusLine();
   }
   //release the connection used by the method
   postMethod.releaseConnection();
   return returnData;
 

}//end getPost

private NameValuePair[] getParams(Map map){

         NameValuePair[] pairs = new NameValuePair[map.size()];
         //Use an Iterator to put name/value pairs from the Map 
           //into the array
         Iterator iter = map.entrySet().iterator();
         int i = 0;
         while (iter.hasNext()){
            
           Map.Entry me = (Map.Entry) iter.next();
            pairs[i] = new NameValuePair(
                      (String)me.getKey(),((String[]) me.getValue())[0]);
           i++;
         }
         return pairs;
}//end getParams

}

      </source>
   
  
 
  



JSP Post Data Viewer

   <source lang="java">

/* <%@page contentType="text/html"%> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <jsp:useBean id="userB" class="com.jexp.UserBean" >

   <jsp:setProperty name="userB" property="*" />

</jsp:useBean> <html> <head><title>Post Data Viewer</title></head> <body>

Here is your posted data

   User name: 
 <c:out value="${userB.username}" />

Department: <c:out value="${userB.department}" />

Email: <c:out value="${userB.email}" />

</body> </html>

  • /

package com.jexp; public class UserBean implements java.io.Serializable{ String username; String email; String department; public UserBean(){} public void setUsername(String _username){

   if(_username != null && _username.length() > 0)
       username = _username;
   else
        username = "Unknown";

} public String getUsername(){

   if(username != null)
       return username;
   else
       return "Unknown"; }

public void setEmail(String _email){

    if(_email != null && _email.length() > 0)
       email = _email;
   else
        email = "Unknown";

} public String getEmail(){

  if(email != null)
       return email;
   else
       return "Unknown";

} public void setDepartment(String _department){

    if(_department != null && _department.length() > 0)
       department = _department;
   else
        department = "Unknown";

} public String getDepartment(){

  if(department != null)
        return department;
   else
       return "Unknown"; 
   }

}

      </source>
   
  
 
  



JSP without beans

   <source lang="java">

//createPerson.jsp <html>

 <head><title>Create Person</title></head>
 <body>

Enter your details

   <form action="displayDetails.jsp" method="post">
First name: <input type="text" name="firstName" />
Last name: <input type="text" name="lastName" />
Age: <input type="text" name="age" />
     <input type="submit" value="Submit details" />
   </form>
 </body>

</html> // displayDetails.jsp <%@ taglib prefix="c" uri="http://java.sun.ru/jstl/core" %> <html>

 <head><title>Display details</title></head>
 <body>

Your details (or, the details you entered!)

First name<c:out value="${param.firstName}" />
Last name <c:out value="${param.lastName}" />
Age <c:out value="${param.age}" />
 </body>

</html>


      </source>
   
  
 
  



Multiple Declaration

   <source lang="java">

<%! int i; %> <%! void foo(){} %> <html>

 <body>
   <%! int j; %>
      String here
   <%! void bar(){} %>
 </body>

</html>

      </source>
   
  
 
  



Output: Creating a Greeting

   <source lang="java">

<HTML>

 <HEAD>
   <TITLE>Creating a Greeting</TITLE>
 </HEAD>
 <BODY>

Creating a Greeting

   <%
       out.println("Hello from JSP!");    //Display the greeting
    %>
 </BODY>

</HTML>


      </source>
   
  
 
  



Passing parameters

   <source lang="java">

//File: passingPara.jsp <jsp:forward page="accessingParameters.jsp">

 <jsp:param name="myParam" value="John Doe"/>

</jsp:forward> //accessingParameters.jsp This page had a parameter forwarded to it:
<%= request.getParameter("myParam") %>


      </source>
   
  
 
  



pwd -- print working directory

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

<html> <head> <title>pwd -- print working directory (aka where r u?)</title> </head> </body>

pwd -- print working directory (aka where r u?)

<p>This JSP will show where this particular Servlet/JSP engine will set your ``current directory"" to when runing servlets/JSPs. In many cases this will be the directory that root/administrator is in when starting the Web Server. <%

 java.io.File f = new java.io.File(".");
%>

<p>Current directory is <%= f.getCanonicalPath() %> <p>Listing:

    <% String[] list = f.list(); for (int i=0; i<list.length; i++) { out.print("
  • " + list[i]); } %>

</body> </html>


      </source>
   
  
 
  



Request header display in a JSP

   <source lang="java">

<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html> <head><title>Request header display</title></head> <body>

Here are all the Request Headers

<c:forEach var="reqHead" items="${header}">

   <c:out value=
       "${reqHead.key}"/>: <c:out value="${reqHead.value}"/>

</c:forEach>

</body> </html>


      </source>
   
  
 
  



Simple JSP output

   <source lang="java">

//ch01_01.jsp <HTML>

 <HEAD>
   <TITLE>A JSP Example</TITLE>
 </HEAD>
 <BODY>

Using JSP

   <% out.println("No worries."); %>
 </BODY>

</HTML>

//ch01_02.html <HTML>

   <HEAD>
       <TITLE>Reading Text Fields</TITLE>
   </HEAD>

   <BODY>

Reading Text Fields

       <FORM ACTION="ch01_03.jsp" METHOD="POST">
           Enter your name:
           <INPUT TYPE="TEXT" NAME="text1">
           
<INPUT TYPE="SUBMIT" value="Submit"> </FORM> </BODY>

</HTML> //ch01_03.jsp <HTML>

 <HEAD>
   <TITLE>Reading Data From Text Fields</TITLE>
 </HEAD>
   <BODY>

Reading Data From Text Fields

       Your name is 
       <% out.println(request.getParameter("text1")); %>
  </BODY>

</HTML> //ch01_07.jsp <HTML>

   <HEAD>
       <TITLE>Using a Bean</TITLE>
   </HEAD>
   <BODY>

Using a Bean

   <% beans.ch01_04 messenger = new beans.ch01_04(); %>
   The bean says: <%= messenger.message() %> 
   </BODY>

</HTML> //ch01_07.jsp <HTML>

   <HEAD>
       <TITLE>Using Bean Properties</TITLE>
   </HEAD>
   <BODY>

Using Bean Properties

       <jsp:useBean id="bean1" class="beans.ch01_06" />
       The bean says: <jsp:getProperty name="bean1" property="message" /> 
       
<jsp:setProperty name="bean1" property="message" value="No Problem." /> Now the beans says: <jsp:getProperty name="bean1" property="message" /> </BODY>

</HTML>


      </source>
   
  
 
  



Simple JSP page to display the random number

   <source lang="java">

<html>

 <HEAD>
   <TITLE>HTML Title</TITLE>
 </HEAD>
 <BODY>
   

Ramdom number from 0 to 10 : <%= (int) (Math.random() * 10) %>

Refresh the page to see if the number changes...

 </BODY>

</HTML>

      </source>
   
  
 
  



Simplest Jsp page: A Web Page

   <source lang="java">

<HTML>

 <HEAD>
   <TITLE>A Web Page</TITLE>
 </HEAD>
 <BODY>
   <% out.println("Hello there!"); %>
 </BODY>

</HTML>

      </source>
   
  
 
  



Welcome page and top level URL

   <source lang="java">

<html> <head> <title>Welcome to jexp</title> </head> <body> Welcome to the welcome page.
You can reach this page by entering the top level URL
for this web application. e.g.
http://www.jexp.ru</body> </html>

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.ru/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <welcome-file-list>

 <welcome-file>index.jsp</welcome-file>

</welcome-file-list> </web-app>


      </source>