Anda di halaman 1dari 41

Java Servlets Java Server Pages (JSP)

Server-side Java for the web


a servlet is a Java program which outputs an html page; it is a server-side technology
HTTP Request HTTP Response Server-side Request
Java Servlet

Response Header + Html file web server

Java Server Page

browser
servlet container (engine) - Tomcat

HelloWorld
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello CS764!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello CS764!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }

<html><head></head> <body> <a href="../servlet/HelloWorld"> <h1>Execute HelloWorld Servlet</h1> </a> </body> </html>

<html> <head> <title>Hello CS764!</title></head> <body> <h1>Hello CS764!</h1> </body> </html>

What is a java servlet ?


a java servlet is a java class extending HTTPServlet class a java servlet class implements the doGet(), doPost() or other equivalent HTTP method and (usually) prints at the standard output an html file a java servlet class can contain any kind of java code the JDK can compile a java servlet class needs to be compiled prior to using it; it must use servlet-api.jar

Apache Tomcat
the most well known servlet/jsp container is a web server + implementation of Java Servlet and JSP (Java Server Pages) APIs is developed by Apache Software Foundation available at http://tomcat.apache.org/ under Apache Software License

Installing Tomcat
1. Download the binary zip distribution (e.g. apachetomcat-6.0.20.zip) in a local folder (we will use c:\temp in the rest of the guide) 2. Set the environment variables JAVA_HOME=path_to_JDK_installation_folder CATALINA_HOME=path_to_tomcat_installation_folder either as Windows system variables or in the files startup.bat and shutdown.bat from the bin directory Ex. place the following lines in the beginning of startup.bat and shutdown.bat: set JAVA_HOME=c:\progra~1\java\jdk1.6.0 set CATALINA_HOME=c:\temp\apache-tomcat-6.0.20

Starting/shutting down Tomcat


start Tomcat from a cmd prompter (window): c:\temp\apache-tomcat-6.0.20\bin\startup.bat verify startup by pointing a browser to the url http://localhost:8080 shutting down Tomcat from a cmd prompter (window): c:\temp\apache-tomcat-6.0.20\bin\shutdown.bat

Tomcat standard folders


bin contains executable files for controlling the server (start, shut down etc.) conf contains configuration files; most important server.xml for configuring the server and web.xml a general configuration file for web applications lib libraries (jars) used by tomcat and deployed web applications logs log files temp temporary files webapps contains the web applications deployed work contains files created by tomcat during running (e.g. it crates a servlet from each jsp file)

Format of a web application


web applications are stored in the webapps folder, either as a folder or as a .war archive a web application (either a folder or a .war archive) must contain the following files:
WEB-INF folder WEB-INF\web.xml: a configuration file

optionally the WEB-INF folder can contain the following subfolders:


classes: which contain servlets lib: which contains jars used by the web application

html, jsp and resource files can be placed anywhere in the web application home folder servlets must be placed in the folder or subfolders of WEBINF\classes

A very simple web.xml example


<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd version="2.5"> </web-app>

Configuring servlets
for JSPs (Java Server Pages) no additional configuration needs to be done for java servlets additional lines must be placed in the web.xml file:
<servlet> <servlet-name>ServletsName</servlet-name> <servlet-class>The_Class_Name_of_the_Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name> ServletsName </servlet-name> <url-pattern>/URL_of_the_servlet</url-pattern> </servlet-mapping>

Client - Server - DB
Trigger Servlet, JSP (Request)

Client (browser)

Through internet

Web server
(Apache, JWS)
Request data

Return html file (Response) Return data

JDBC, intranet

Database server (DB2)

Life Cycle of Servlet


servlet GenericServlet init(ServletConfig); service(ServletRequest,
ServletResponse);

HttpServlet

doGet(HttpServletRequest,
HttpServletResponse);

doPost(HttpServletRequest,
destroy();
HttpServletResponse);

Interaction with Client


HttpServletRequest
String getParameter(String) Enumeration getParameters(String[])

HttpServletResponse
Writer getWriter() ServletOutputStream getOutputStream()

Handling GET and POST Requests

Assignment 2: Get Stock Price


Ass2.html
<html><head></head> <body>

<form action="../servlet/Ass2Servlet" method=POST>


<h2>Stock Symbol name: <input type=text name="stockSymbol"></h2><br> <input type="submit" value = "get price"> </form> </body></html>

Client Side

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

Ass2Servlet

public class Ass2Servlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String stockSymb = request.getParameter("stockSymbol"); StockGrabber sg = new StockGrabber(); sg.setStockSymbol(stockSymb); // Set the stock symbol as input String stockPrice = sg.getPrice();// Get the price of stock System.out.println("After StockGrabber.getPrice --"+stockPrice);// Debug out.println("<html><head></head><body><br><br>"); out.println(stockSymb + " -- " + stockPrice); out.println("<hr>"); out.println("<form action=\"../servlet/Ass2Servlet\" method=POST>"); out.println("<h3>Stock Symbol name: <input type=text name=\"stockSymbol\"></h3>"); out.println("<input type=submit value=\"get price\">"); out.println("</form>"); out.println("</body></html>"); }

JSP
JSP (Java Server Page) JSP HTML, XML Tomcat Apache Java Compiler James Duncan Davidson ..2000 Servlet Byte Code

JSP (x.jsp)
DOS>explorer http://localhost:8080/x.jsp

<% for (int i=1;i<=10;i++){ out.println(i); } %> <b>bye</b>

Java Server Pages (JSP)


Clients Computer

1.Browser requests HTML 7. Server sends HTML back to browser

Server

6. Java Engine sends HTML to server


servlet servlet 5.The servlet runs and generates HTML 2. Server sends requests to Java Engine

class

Bean

3. If needed, the Java Engine reads the .jsp file


4. The JSP is turned into a servlet, compiled, and loaded

Java Engine

A First JSP
<html> <head></head> <body> <p>Enter two numbers and click the calculate button.</p> <form action=calculator.jsp method=get> <input type=text name=value1><br> <input type=text name=value2 ><br> <input type=submit name=calculate value=calculate> </form> </body> </html>

Calculator.html

<html> <head><title>A simple calculator: results</title></head> <body> <%-- A simpler example 1+1=2 --%> 1+1 = <%= 1+1 %> <%-- A simple calculator --%> <h2>The sum of your two numbers is:</h2> <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %> </body> </html>

Calculator.jsp

What is a Java Server Page (JSP)


an html file containing parts of java code; the java code is placed inside the <% %> tags or some other related tags Tomcat will create a servlet from the jsp file (which will be saved in the work folder) when the jsp is requested the servlet is executed and the output of the server is sent back to the client

When Tomcat needs to use a JSP page, it:


How JSP works

Translates the JSP into a Java servlet Compiles the servlet Creates one instance of the JSP servlet Executes the servlet as normal Java code Hence, when you are writing JSP, you are writing higher-level Java code

Each call to the JSP servlet is executed in a new Thread


Since there is only one JSP object, you have to use synchronization if you use any instance variables of the servlet

You have two basic choices when using JSP:


Let the JSP do all the work of a servlet Write a servlet that does the work and passes the results to JSP to create the resultant HTML page
This works because a servlet can call another servlet

Bottom line: JSP is just a convenient way of writing Java code!

JSP scripting elements


There is more than one type of JSP tag, depending on what you want done with the Java <%= expression %>
The expression is evaluated and the result is inserted into the HTML page

<% code %>


The code is inserted into the servlet's service method If code contains declarations, they become local variables of the service method This construction is called a scriptlet

<%! declarations %>


The declarations are inserted into the servlet class, not into a method Hence, declarations made here become instance variables

<HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML>

Example JSP

Notes:
The <%= ... %> tag is used, because we are computing a value and inserting it into the HTML The fully qualified name (java.util.Date) is used, instead of the short name (Date), because we havent yet talked about how to do import declarations

Variables
You can declare your own variables, as usual JSP provides several predefined variables request : The HttpServletRequest parameter response : The HttpServletResponse parameter session : The HttpSession associated with the request, or null if there is none out : A JspWriter (like a PrintWriter) used to send output to the client Example: Your hostname: <%= request.getRemoteHost() %>

Scriptlets
Scriptlets are enclosed in <% ... %> tags
Scriptlets are executable code and do not directly affect the HTML Scriptlets may write into the HTML with out.print(value) and out.println(value) Example: <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %>

Scriptlets are inserted into the servlet exactly as written, and are not compiled until the entire servlet is compiled
Example: <% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% } else { %> Have a <B>lousy</B> day! <% } %>

One of the principle motivations for JSP is to allow Web designers who are not Java programmers to get some of the features of Java into their pages Hence, in some cases it is desirable to put as little actual Java into your JSP as possible Where this is a goal, a better approach is to provide the necessary Java functionality via methods in a class which is loaded along with the servlet

The case against scriptlets

Declarations
Use <%! ... %> for declarations to be added to your servlet class, not to any particular method
Caution: Servlets are multithreaded, so nonlocal variables must be handled with extreme care If declared with <% ... %>, variables are local and OK If declared with <%! ... %>, variables may need to be synchronized Data can also safely be put in the request or session objects

Example: <%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %> You can use <%! ... %> to declare methods as easily as to declare variables

Directives
Directives affect the servlet class itself A directive has the form: <%@ directive attribute="value" %> or <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> The most useful directive is page, which lets you import packages
Example: <%@ page import="java.util.*" %>

The include directive


The include directive inserts another file into the file being parsed The included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directives Syntax: <%@ include file="URL " %> The URL is treated as relative to the JSP page If the URL begins with a slash, it is treated as relative to the home directory of the Web server The include directive is especially useful for inserting things like navigation bars

JSP in XML
JSP can be embedded in XML as well as in HTML Due to XMLs syntax rules, the tags must be different (but they do the same things) HTML: <%= expression %> XML: <jsp:expression>expression</jsp:expression> HTML: <% code %> XML: <jsp:scriptlet>code</jsp:scriptlet> HTML: <%! declarations %> XML: <jsp:declaration>declarations</jsp:declaration> HTML: <%@ include file=URL %> XML: <jsp:directive.include file="URL"/>

Comments
You can put two kinds of comments in JSP:
<!-- HTML comment -->
This is an ordinary HTML comment, and forms part of the page that you send to the user Hence, the user can see it by doing View source JSP scriptlets in HTML comments will be executed

<%-- JSP comment -->


This kind of comment will be stripped out when the JSP is compiled Its intended for page developers; the user will never see it

JSP Tags
Comments <%-- ...text... --%> Declaration <%! int i; %> <%! int numOfStudents(arg1,..) {} %> Expression <%= 1+1 %> Scriptlets <% java code %> include file <%@ include file=*.jsp %> ...

Using Java Bean


Declaration
1. <jsp:useBean id=bean1 class=Bean1/> 2. <jsp:useBean id=bean1 class=Bean1 name=serBean type=SerBean1/>

Setting property
1. <jsp:setProperty name=bean1 property=color value=red/> 2. <jsp:setProperty name=bean1 property=color/> 3. <jsp:setProperty name=bean1 property=color param=bgColor/> 4. <jsp:setProperty name=bean1 property=*/>

Getting property
1. <jsp:getProperty name=bean1 property=color/> 2. <%=bean1.getColor() %>

Assg2 example
<html> <head></head> <body> <center> <table border = 0> <form action=ass2.jsp method = POST> <tr><td><font color=blue>choose a stock market:</font></td> <td><select name="stockMarket"> <option value="Waterhouse">Waterhouse</option> <option value="Yahoo">Yahoo</option> <option value="ChicagoStockex">Chicago Stockex</option> <option value="Reuters">Reuters</option> </select></td> </tr> <tr><td><font color = blue>input a stock symbol:</font></td> <td><input type="edit" name="stockSymbol" size=15></td> </tr> <tr><td></td><td><input type="submit" value = "get price"></td></tr> </table> </form></center> </body></html>

Client side
Ass2.html

ass2.jsp
<html><head> <jsp:useBean id="ass2" scope="session" class="ass2.StockGrabber" /> <jsp:setProperty name="ass2" property="*" /> </head> <body><h2><% <jsp:setProperty name=ass2 property=stockSymbol/> ass2.processInput(); <jsp:setProperty name=ass2 property=stockMarket/> ass2.getPrice(); %> <center><table border=5> <tr><td># of data</td> <td>Stock Market</td> <td>Stock Symbol</td> <td>Stock Price </td> </tr><% String[] stockMarkets = ass2.getStockMarkets(); String[] symbols = ass2.getSymbols(); String[] prices = ass2.getPrices(); for(int i=0; i<prices.length; i++){ %> <tr><td> <%= i+1 %> </td> <td> <%= stockMarkets[i] %> </td> <td> <%= symbols[i] %> </td> <td><font color=red><%= prices[i] %></font></td> </tr><% } %> </table> </center> </h2> <hr><%@include file="ass2.html" %></html>

Server side

Without using JDBC


Public class StockGrabber { ... public void processInput(){ if(stockMarket.compareTo("Waterhouse")==0){ setPrePriceString("<!--Last-->"); setPostPriceString("</FONT>"); setUrlPrefix("http://research.tdwaterhouse.com/ waterhouse/quote.asp?ticker="); } else if(stockMarket.compareTo("Yahoo")==0){ setPrePriceString("<td nowrap><b>"); setPostPriceString("</b></td>"); setUrlPrefix("http://finance.yahoo.com/q?s="); } ... else if(...){} ... else{...} } ... }

Using JDBC --> Database


import java.sql.*; Public class StockGrabber { ... public void processInput(){
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String sourceURL="jdbc:odbc:stockInfo"; Connection databaseConnection=DriverManager.getConnection(sourceURL); Statement statement=databaseConnection.createStatement(); ResultSet info =statement.executeQuery( "select tPrePriceStr, tPostPriceStr, tUrlPrefix from stockMarketData where tStockMarket = stockMarket); while(inf.next()) { prePriceString = info.getString(tPrePriceStr"); postPriceString = info.getString(tPostPriceStr); urlPrefix = info.getString(tUrlPrefix); }

catch(SQLException e){ ... } ... } }

Anda mungkin juga menyukai