Professional Documents
Culture Documents
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>
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
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
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
JDBC, intranet
HttpServlet
doGet(HttpServletRequest,
HttpServletResponse);
doPost(HttpServletRequest,
destroy();
HttpServletResponse);
HttpServletResponse
Writer getWriter() ServletOutputStream getOutputStream()
Client Side
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
Server
class
Bean
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
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
<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
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.*" %>
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 Tags
Comments <%-- ...text... --%> Declaration <%! int i; %> <%! int numOfStudents(arg1,..) {} %> Expression <%= 1+1 %> Scriptlets <% java code %> include file <%@ include file=*.jsp %> ...
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