Java/JSP/Basics

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Advanced Dynamic Web Content Generation. 1

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





Comments in JSP page

<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>





CSS, JavaScript, VBScript, and JSP 1

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





CSS, JavaScript, VBScript, and JSP 2

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





Declaration Tag Example

<%!
  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>





Declaration Tag - Methods

<%!
  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>





Embedding Code

<%!
  String[] names = {"Green", "White", "Black", "Red"};
%>
<HTML>
  <HEAD><TITLE>Embedding Code</TITLE></HEAD>
  <BODY>
    <H1>List of people</H1>
    <TABLE BORDER="1">
      <TH>Name</TH>
      <% for (int i=0; i<names.length; i++) { %>
        <TR><TD><%= names[i]%></TD></TR>
      <% } %>
    </TABLE>
  </BODY>
</HTML>





Expression Language Examples

<html>
<head>
<title><!-- be aware that this listing will not work
in Tomcat 4.1, or any other container that does
not support the use of the expression language outside
of tags -->
<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}">
<h1>Welcome to the ${param.department} Department</h1>
Here are some basic comparisons:
<p>
Is 1 less than 2? ${1<2} <br>
Does 5 equal 5? ${5==5} <br>
Is 6 greater than 7? ${6 gt 7}<br>
<p>Now for some math:<br>
6 + 7 = ${6+7}<br>
8 x 9 = ${8*9}<br>

<hr>You appear to be using the following browser:
${header["user-agent"]}
</body>
</html></title>





JSP Basics ch02

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





JSP Basics: Dynamic Page Creation for Data Presentation 2

/*
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>
<table class="mainBox" width="400">
<tr><td class="boxTitle" colspan="2">
Wrox JSP Portal Selector
</td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td>
<form  action="showportal.jsp" method="get">
<table>
<tr>
<td width="200">Portal Selection</td><td>
<select name="portchoice">
<option>news</option>
<option>weather</option>
<option>entertainment</option>
</select>
</td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td colspan="2" align="center">
<input type="submit" value="Select"/>
</td></tr>
</table>
</form>
</td></tr></table>
</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>
       <h1>Application logic problem detected!</h1>   
    </c:otherwise>
</c:choose>
</body>
</html>

//news.jsp
<head>
<link rel=stylesheet type="text/css" href="portal.css">
<title>News Portal</title>
</head>
<body>
<table class="mainBox" width="600">
<tr><td class="boxTitle" >
Welcome to the News Portal!
</td></tr>
<tr><td> 
<span class="headLine">
<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>
</span>
<span class="newsText">
<jsp:include page="dummytext.html" />
</span>
</td></tr>
</table>





JSP Basics: Generalized Templating and Server Scripting 1

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





JSP Basics: Generalized Templating and Server Scripting 2

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





JSP Basics: Generalized Templating and Server Scripting 3

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





JSP Best Practices and Tools

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





JSP Directives

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





JSP Directives: your page

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





JSP Expression Language

<%-- <%@page isScriptingEnabled="true" %> --%>
<html>
<head>
<title>Using the JSP Expression Language</title>
</head>
<body>
<h1>The Expression Language</h1>
The value of the name is ${header.userAgent}.

</body>
</html>





JSP: expression language 2

JSP Initialization

<?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:
<br>
<%= pageContext.getServletConfig().getInitParameter("testParam") %>
</body>
</html>





JSP in J2EE

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





JSP Model 2

JSP Passing Parameters

JSP Performance

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





JSP post

//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>
<h2>Here is your posted data</h2>
<c:forEach var="map_entry" items="${param}">
    <strong><c:out value="${map_entry.key}" /></strong>: 
  <c:out value="${map_entry.value}" /><br><br>
</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
}





JSP Post Data Viewer

/*
<%@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>
<h2>Here is your posted data</h2>
    <strong>User name</strong>: 
  <c:out value="${userB.username}" /><br><br>
   <strong>Department</strong>: 
  <c:out value="${userB.department}" /><br><br>
   <strong>Email</strong>: 
  <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"; 
    }
}





JSP without beans

//createPerson.jsp
<html>
  <head><title>Create Person</title></head>
  <body>
    <h1>Enter your details</h1>
    <form action="displayDetails.jsp" method="post">
      <table>
        <tr><td>First name:</td>
            <td><input type="text" name="firstName" /></td>
        </tr>
        <tr><td>Last name:</td>
            <td><input type="text" name="lastName" /></td>
        </tr>
        <tr><td>Age:</td>
            <td><input type="text" name="age" /></td>
        </tr>
      </table>
      <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>
    <h1>Your details (or, the details you entered!)</h1>
    <table>
      <tr><td>First name</td><td><c:out value="${param.firstName}" /></td></tr>
      <tr><td>Last name</td> <td><c:out value="${param.lastName}"  /></td></tr>
      <tr><td>Age</td>       <td><c:out value="${param.age}"       /></td></tr>
    </table>
  </body>
</html>





Multiple Declaration

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





Output: Creating a Greeting

<HTML>
  <HEAD>
    <TITLE>Creating a Greeting</TITLE>
  </HEAD>
  <BODY>
    <H1>Creating a Greeting</H1>
    <%
        out.println("Hello from JSP!");    //Display the greeting
     %>
  </BODY>
</HTML>





Passing parameters

//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:<br>
<%= request.getParameter("myParam") %>





pwd -- print working directory

/*
 * 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>
<h1>pwd -- print working directory (aka where r u?)</h1>
<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:
<ul>
<% 
  String[] list = f.list();
  for (int i=0; i<list.length; i++) {
    out.print("<li>" + list[i]);
  }
 %>
</ul>
</body>
</html>





Request header display in a JSP

<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %>
<html>
<head><title>Request header display</title></head>
<body>
<h2>Here are all the Request Headers</h2>
<c:forEach var="reqHead" items="${header}">
    <strong><c:out value=
        "${reqHead.key}"/></strong>: <c:out value="${reqHead.value}"/><br />
        
</c:forEach>

</body>
</html>





Simple JSP output

//ch01_01.jsp
<HTML>
  <HEAD>
    <TITLE>A JSP Example</TITLE>
  </HEAD>
  <BODY>
    <H1>Using JSP</H1>
    <% out.println("No worries."); %>
  </BODY>
</HTML>

//ch01_02.html
<HTML>
    <HEAD>
        <TITLE>Reading Text Fields</TITLE>
    </HEAD>
 
    <BODY>
        <H1>Reading Text Fields</H1>
        <FORM ACTION="ch01_03.jsp" METHOD="POST">
            Enter your name:
            <INPUT TYPE="TEXT" NAME="text1">
            <BR>
            <INPUT TYPE="SUBMIT" value="Submit">
        </FORM>
    </BODY>
</HTML>
//ch01_03.jsp
<HTML>
  <HEAD>
    <TITLE>Reading Data From Text Fields</TITLE>
  </HEAD>
    <BODY>
        <H1>Reading Data From Text Fields</H1>
        Your name is 
        <% out.println(request.getParameter("text1")); %>
   </BODY>
</HTML>
//ch01_07.jsp
<HTML>
    <HEAD>
        <TITLE>Using a Bean</TITLE>
    </HEAD>
    <BODY>
        <H1>Using a Bean</H1>
    <% 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>
        <H1>Using Bean Properties</H1>
        <jsp:useBean id="bean1" class="beans.ch01_06" />
        The bean says: <jsp:getProperty name="bean1" property="message" /> 
        <BR>
        <jsp:setProperty name="bean1" property="message" value="No Problem." />
        Now the beans says: <jsp:getProperty name="bean1" property="message" />
    </BODY>
</HTML>





Simple JSP page to display the random number

<html>
  <HEAD>
    <TITLE>HTML Title</TITLE>
  </HEAD>
  <BODY>
    
    <H3 ALIGN="CENTER">
      Ramdom number from 0 to 10 : 
      <FONT COLOR="RED">
        <%= (int) (Math.random() * 10) %>
      </FONT>
    </H3>
    <H4 ALIGN="CENTER">Refresh the page to see if the number changes...</H4>
  </BODY>
</HTML>





Simplest Jsp page: A Web Page

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





Welcome page and top level URL

<html>
<head>
<title>Welcome to jexp</title>
</head>
<body>
Welcome to the welcome page. 
<br>You can reach this page by entering the top level URL
<br>for this web application. e.g.
<br>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>