Title: Servlet and JSP
1Servlet and JSP
C. Edward Chow
Related references Head First Servlets
JSPhttp//tomcat.apache.org/tomcat-5.5-doc/index.
htmlJavaServer Pages (JSP) Specfication, Version
2.0 Servlet API Specification, Version 2.4 Java
Tutorial Book on JDBC J2EE tutorial on
Servlet J2EE tutorial on JSP J2EE tutorial on
Java Standard Tag Library
2Servlet
- A servlet is a JavaTM technology-based Web
component, managed by a container, that generates
dynamic content. --- Servlet API Specification,
Version 2.4 - The servlet container is a part of a Web server
or application server that provides the network
services over which requests and responses are
sent, decodes MIME-based requests, and formats
MIME-based responses. A servlet container also
contains and manages servlets through their
lifecycle
3Web App Processing with Servlet
URL
4Web App Processing with Servlet
Apache forwards HTTP request to Tomcat Using AJP
protocol
5Web App Processing with Servlet
Tomcat uses the mapping info in a configuration
file called web.xml of the web application to
find the right servlet
6Web App Processing with Servlet
Tomcat uses the mapping info in a configuration
file called web.xml of the web application to
find the right servlet
7Web App Processing with Servlet
8Web App Processing with Servlet
9What Container Provides?
- Communication Support (to web server no socket
code) - Lifecycle Management of Servlet(loading
instantiating initializing invoking garbage
collection fault tolerance) - Multithread Support(create threat for each
servlet request) - Declarative Security(use XML deployment
descriptor to configure/modify security without
having to hard-code it into servlet code) - JSP Support(translating that JSP code into real
java)
10What a Simple Servlet looks Like?
- import javax.servlet.
- import javax.servlet.http.
- import java.io.
- public class SimpleServlet extends HttpServlet
- public void doGet (HttpServletRequest request,
HttpServletResponse response) throws IOException
- PrintWriter out response.getWriter()
- java.util.Date today new
java.util.Date() - out.println("lthtmlgtltbodygtlth1gtThis is a
simple web page generated by SimpleServlet with
date info.lt/h1gtltbrgtToday is "today"lt/bodygtlt/html
gt") -
-
11What a Servlet Code looks Like?
- package com.example.web
- import com.example.model.
- import javax.servlet.
- import javax.servlet.http.
- import java.io.
- import java.util.
- public class BeerSelect extends HttpServlet
- public void doPost (HttpServletRequest
request, - HttpServletResponse
response) - throws IOException, ServletException
- String c request.getParameter("color")
- BeerExpert be new BeerExpert()
- List result be.getBrands(c)
- request.setAttribute("styles", result)
- RequestDispatcher view
- request.getRequestDispatcher("result.jsp")
- view.forward(request, response)
-
-
12How Does Container Find Right Servlet?
- Using the Deployment Descriptor web.xml
- ltweb-app xmlns"http//java.sun.com/xml/ns/j2ee"
xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
ce" xsischemaLocation"http//java.sun.com/xml/ns
/j2ee http//java.sun.com/xml/ns/j2ee/web-app_2_4.
xsd" version"2.4"gt - ltservletgt
- ltservlet-namegt CS301 Simple Servletlt/servlet-nam
egt - ltservlet-classgt SimpleServletlt/servlet-classgt
- lt/servletgt
- ltservlet-mappinggt
- ltservlet-namegt CS301 Simple Servletlt/servlet-nam
egt - lturl-patterngt /s1lt/url-patterngt
- lt/servlet-mappinggt
- lt/web-appgt
- This mapping improves flexibility and security.
How?
13A Simple Web Application Following
Model-View-Controller Design Pattern
Servlet
Controllere.g. BeerSelect.java
Class Beer //Business//Logic
ltJSP gt
Model e.g., BeerExpert.java
Viewe.g. result.jsp
14File Structure in A Java Web Development
Environment
ltwebappgt Web.xml lt/webappgt
ltresult.jsp gt
BeerExpert.java
BeerSelect.java
15File Structure in a Java Web Deployment
Environment
ltwebappgt Web.xml lt/webappgt
Form.html
ltresult.jsp gt
BeerExpert.java
BeerSelect.java
16Java-base Web Application Development Environment
Setup
- We will use the tomcat 5.5.12 java-based web
container and share jdk1.5.0_03 in
cs301/public_html/java - cp r cs301/public_html/tomcatChow
ltlogingt/public_html - It contains examples with
- The above MVC Beer-v1 web application
- Servlet with JDBC using mysql
- JSP pages using SQL tags provided by JavaServer
Page Standard Tag Library (JSTL). - Set up Environment Variable for JAVA_HOME and
CATALINA_HOME - Setup server.xml with your own tomcat port number
and mysql Datasource info. - Setup tomcat-users.xml with user and admin
passwords
17JDK Environment Setup
- For CSH user, (check echo SHELL) edit your
.cshrc file with the following - setenv JAVA_HOME /users/server/students/cs301/publ
ic_html/java/jdk1.5.0_03 - setenv path /users/server/students/cs301/public_h
tml/java/jdk1.5.0_03/binPATH - setenv CATALINA_HOME /users/server/students/ltlogin
gt/public_html/tomcatChow - For BASH user, (check echo SHELL) edit
.bash_profile - PATH/users/server/students/cs301/public_html/java
/jdk1.5.0_03/binPATHHOME/bin - JAVA_HOME/users/server/students/cs301/public_html
/java/jdk1.5.0_03 - CATALINA_HOME/users/server/students/ltlogingt/publi
c_html/tomcatChow - export PATH JAVA_HOME CATALINA_HOME
- Once this is setup you can use CATALINA_HOME in
shell commands, e.g., cd CATALINA_HOME to get
to your own tomcat directory.
18Setup Server Ports in server.xml
- Edit the server.xml in CATALINA_HOME/conf
directory - Change the port number so that we can all run
tomcat on CS Unix machines. - Spread out using windom or your designated server
machine as php exercises. Make sure you shutdown
server after you exercise run
CATALINA_HOME/bin/shutdown.sh - Find the lines with the following content
- lt!-- Define a non-SSL HTTP/1.1 Connector on port
8080 --gt - ltConnector port"8080" maxHttpHeaderSize"8192
" - maxThreads"150" minSpareThreads"25"
maxSpareThreads"75" - enableLookups"false"
redirectPort"8443" acceptCount"100" - connectionTimeout"20000"
disableUploadTimeout"true" /gt - Replace port 8080 with 9ltlast 3 digits of your
SIDgt in ltConnectorgt element. - Find ltServer port"8005" shutdown"SHUTDOWN"gt
- Replace port 8005 with 7ltlast 3 digits of your
SIDgt in ltServergt element.
19Setup Database Resource in Server.xml
- To share the Database connections among web
application, we add the following ltContextgt and
ltResourcegt tags to server.xml before lt/hostgt - ltContext path"/sql" docBase"sql"
- debug"5" reloadable"true"
crossContext"true"gt - ltResource name"jdbc/InventoryDB"
auth"Container" - type"javax.sql.DataSource"
- maxActive"100" maxIdle"30" maxWait"10000"
- username"cs301" passwordXXXXXXXX"
- driverClassName"com.mysql.jdbc.Driver"
- url"jdbcmysql//blanca.uccs.edu3306
/cs301db?autoReconnecttrue"/gt - lt/Contextgt
20Basic Commands for compilation and Start/Shutdown
Tomcat
- Javac classpath CATALINA_HOME/common/lib/servlet
-api.jarclasses. d classes src/com/example/web/
BeerSelect.java-d specifies that compiled
classes should be put in the classes directory.
Here CATALINA_HOME is an environment variable
with full path to the install directory of
tomcat. - Often we use ant (or asant for Sun App Server)
utility or IDE such as NetBeans/IBM RSA to
facilitate the compilation and deployment web
applications. They contain the basic compilation
commands as above. - Here are the commands for shutdown/start tomcat.
We often needs to do that after creating a new
classes or DD.Some application servers
automatically scan new files and redeploy - cd CATALINA_HOME
- bin/shutdown.sh
- bin/startup.sh
21Servlet with JDBC demo
- import java.sql.
- import javax.sql.
- public class InventoryDBServlet extends
HttpServlet - Driver D
- Connection con
- Statement stmtPrintWriter out
response.getWriter() - try
- Class.forName("org.gjt.mm.mysql.Driver").new
Instance() - catch(java.lang.ClassNotFoundException e)
- System.err.print("ClassNotFoundException
e.getMessage()) -
- String url"jdbcmysql//blanca.uccs.edu3306/"da
tabase"?user"user"password"passwd - con DriverManager.getConnection(url)
- stmt con.createStatement()
- String sqlcmd "select from inventory"
- ResultSet rs stmt.executeQuery(sqlcmd)
- while (rs.next())
- StringBuffer itemName new
StringBuffer(rs.getString(1)) - StringBuffer amount new
StringBuffer(rs.getString(2))
22JSP with JSTL SQL Tag Demo
- lt_at_ taglib prefix"c" uri"http//java.sun.com/jsp
/jstl/core" gt - lt_at_ taglib uri"http//java.sun.com/jsp/jstl/sql"
prefix"sql" gt - ltsqlquery var"rs" dataSource"jdbc/InventoryDB"gt
select price.item, price.unitPrice,
inventory.amount from price, inventory where
price.item inventory.item - lt/sqlquerygt
- lthtmlgt ltheadgt lttitlegtDBcataloglt/titlegt lt/headgt
ltbodygt - lth2gtDB Catalog Retrieval Resultslt/h2gt
- lttable border1gt lttr bgcolor"EEDDCC"gtltthgtitemlt/
thgtltthgtunitPricelt/thgtltthgtamountlt/thgtlt/trgt ltcset
var"counter" value"1" /gt ltcforEach
var"row" items"rs.rows"gt ltcchoosegt
ltcwhen test"counter mod 2 0"gt lttr
bgcolor"99EEFF"gt lt/cwhengt
ltcotherwisegt lttr bgcolor"99FFAA"gt
lt/cotherwisegt lt/cchoosegt lttd
aligncentergtrow.itemlt/tdgt lttd
alignrightgtrow.unitPricelt/tdgt lttd
alignrightgtrow.amountlt/tdgt lt/trgt ltcset
var"counter" value"counter1" /gt
lt/cforEachgt - lt/tablegt lt/bodygt lt/htmlgt
23JSP with SQLUPDATE Parameter Access
- Demo http//windom.uccs.edu9888/sql/passwd.jsp
- Source
- lt_at_ taglib prefix"c" uri"http//java.sun.com/jsp
/jstl/core" gt - lt_at_ taglib uri"http//java.sun.com/jsp/jstl/sql"
prefix"sql" gt - lt!-- cset tag need to terminate with /gt --gt
- ltcset var"login" value"param.login" /gt
- ltcset var"password" value"param.password"
/gt - ltcif test"!empty login and !empty password"gt
- ltsqlupdate var"result" dataSource"jdbc/Inv
entoryDB" - sql"insert into password values (?, ?)"
gt - ltsqlparam value"login" /gt
- ltsqlparam value"password" /gt
- lt/sqlupdategt
- lt/cifgt
- Note that we really do not need to set
login/password variable. Just use directly in
ltsqlparam value"param.login" /gt and in
ltcifgt