S LT LT 1 Servlets: Lecture 1 The Basics: ELE406, 2012, Karen Shoop
S LT LT 1 Servlets: Lecture 1 The Basics: ELE406, 2012, Karen Shoop
EECS
EECS
<input type="text" name="age">enter age<br> <input type="text" name="height">enter height</input><br> <input type="text" name="weight"></input>enter height<br> g <input type="text" name="salary"/>enter height<br>
EECS
<select name="nationality"> <option>british i bii h <option>french </select> / l <select name="town"> <option>london</option> <option>paris</option> </select>
EECS
EECS
Tips: save the file as sendName.html (if you are not using an IDE use eg Notepad not Word as Word may store some characters that impact on the page; one EECS common error is to forget the .html extension). Note, we do not know the name of6 h l l l f h ( b ll d )
EECS
HTTP response
response page
php container/plug in
Still HTTP
EECS
php script
8
EECS
Webpage 1
Servlet s Servlets responsibilities: 1. Get users name from HTTP p g 2. Write a webpage 3. Add the users name 4. Send back in HTTP response
10
public class GetEchoServlet extends HttpServlet{ public void doGet(HttpServletRequest request request, HttpServletResponse response) throws IOException, ServletException { String userName = request.getParameter(fullname); response.setContentType("text/html"); response setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(<html><body>Hello); if(userName!=null) if( N ! ll) Validate! out.println(userName); else out.println(mystery person); out.println(</body></html>);}}
EECS 11
EECS
Thinking ahead (JavaScript validation): height type safety (numberint) and value safety (eg >100)
13
BMI Servlet
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
public class BMIServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
public class HelloServlet extends HttpServlet{ public void do______(HttpServletRequest request, do (HttpServletRequest request HttpServletResponse response) throws IOException, ServletException { ___________________________________ ___________________________________ response.setContentType("text/html"); PrintWriter out = response.getWriter(); ______________________________________ ______________________________________ }//end of method }//end of class
EECS 15
cgi
service() () method
request
request responseservlet
php
response page
Tomcat plug in
EECS
17
EECS
19
Also
More generally, manages the lifecycle of its servlets
Calls constructor, init, service, destroy also invokes methods of any listening classes that a servlet implements
It has a main and is working all the time main all time Provides declarative security using settings in Deployment Descriptor (Tomcat: web.xml) web xml) Provides JSP support
EECS 20
public class AnyServlet extends GenericServlet { public AnyServlet() {} // constructor BUT USE THE DEFAULT // NEVER ANY NEED TO WRITE ONE
public void init(ServletConfig config) throws ServletException; // The method actually called by container when servlet is // first created or loaded public void service(ServletRequest req, ServletResponse res) throws ServletException IOException; ServletException, // called by a new thread (in the container) each time a request is received. public void destroy(); // called when servlet is destroyed or removed
EECS } 21
Call constructor
Exists but not ready for work
at server shutdown
doTrace(..) If HTTPServlet
22
HttpServlet
service
Class objects bj t
doGet doPost
service()
EECS
instance
23
Life Cycle
Constructor:
NOT written or called by a developer
no args
EECS
26
maps internal name to fully qualified class name name. (except without .class)
If using remote Tomcat in the ITL: you MUST add servlet/ in front of the action value in <FORM>, and / /servlet/ before the url-pattern in web.xml / p
HTML:
<FORM method=post th d t action=servlet/MyTest.do>
Server (webapps): Se ve
WEB-INF/classes/Echo.class
<servlet> <servlet-name>.</servlet-name> <servlet-class>..</servlet-class> <servlet-class> </servlet-class> </servlet> <servlet-mapping> <servlet-name>.</servlet-name> servlet name . /servlet name <url-pattern></url-pattern > </servlet-mapping> <servlet> <servlet-name>.</servlet-name> <servlet-class>..</servlet-class> </servlet> <servlet-mapping> <servlet-name>.</servlet-name> <url-pattern></url-pattern > </servlet-mapping>
29
HTML:
<FORM method=post action=servlet/Test> ti l t/T t>
Server (webapps):
WEB-INF/classes/foo/Name.class WEB INF/classes/foo/Name class
EECS
EECS
30
EECS
31
Inside classes
EECS
32
Inside chain
EECS
33
Inside classes/chain/web
EECS
34
Inside classes/chain/model
EECS
35
EECS
36
The code for the Chaining2005 Ch i i 2005 web b app The corresponding folder p g
EECS
37
This has same structure as classes seen before but with source code aide memoir
EECS 38
SmallForm.html
<html><title>Sending Form Information to a Servlet</title> <body> <form method="post action=servlet/ProcessSmallForm> Please input your login: <br> <input type="text" name="Login"> i i <input type="submit" value="Login"> </form> </f > </body> </html>
EECS
39
Homework: Write the deployment descriptor ( (web.xml) and the servlet (uname.class to be ) ( stored inside ele406 directory)
EECS
40
Path in webapps
To invoke a servlet
Apache
Must contain /servlet/ because of the way Apache is configured in the ITL
http://tomcat_stu.dcs.qmul.ac.uk/ karens/servlet/CC You can add a classes folder, html and jsp files in karens and edit the existing web.xml <servlet-mapping> <servlet-name>My Servlet</servlet-name> <url-pattern> /servlet/CC </url-pattern > </servlet-mapping> 41
NB You
cannot create subdirectories each with their own web.xml (but if you are using Netbeans or Tomcat on your own machine you can)
EECS
Prior to initialisation the ServletConfig object is created by the container One ServletConfig object per servlet
Container uses it to pass deploy-time information to the servlet
Facts you do not want to hard code into the servlet, e.g. DB name
EECS
42
EECS
43
EECS
45
EECS
46
init()
Not usually overridden BUT may override if:
If connecting to a Database only want to do this once
But would this servlet be the only servlet that needs to connect to that database? Other solutions may be better
M need t register with other objects May d to it ith th bj t Read information in from a file (eg proxy database)
Thinking ahead: servletContext objectwhen we need to share/set information for servlets in the same application.
EECS 47
Instance Variables
public class SillyClass extends HttpServlet{ private int age; public void init(){ Remember init is only ever called once age=0; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ ) th IOE ti S l tE ti { age = Integer.parseInt(request.getParameter(age)); response.setContentType(text/html); p yp ( ); PrintWriter out = response.getWriter(); out.println(<HTML><BODY>You are +age+ weeks old); out.println(</BODY></HTML>); }}
EECS
48
age=?
SillyClass //thread
SillyClass //thread
SillyClass //thread
16
20
28
EECS
49
Solution 2:
Synchronisation lock that makes a variable threadsafe [find out more in the Threads lecture or read Head First J ] Fi Java]
EECS 50
EECS
EECS
53
EECS
55
How to call a servlet in an HTML form What a deployment descriptor does How to write a servlet Where to deploy files How to access client information Servlet life-cycle Initialisation g ServletConfig ServletContext
56
Typically,
the servlet handles the HTTP protocol and coordination of which other servlets & auxiliary class methods to call J Java classes/ beans the business logic (model), l /b th b i l i ( d l) Java Server Pages the presentation logic (view)
EECS
58
Convenient
P id i f t t Provides infrastructure that parses and decodes HTML forms th t dd d f
Powerful
Can communicate directly with web server Multiple servlets can share database connections Simplifies session tracking p g
EECS 59
obtain parameters p Then String[] getParameterValues(String) to obtain an array of values for each one y
returns null if unknown parameter returns a single string () if parameter has no values
EECS 60
A Big Form
EECS
61
BigForm.html
<form action= http://localhost:8080/servlet/elem004.ProcessBigForm action="http://localhost:8080/servlet/elem004 ProcessBigForm" method="post"> Single value parameters Please enter: <br><br> Your login: <input type="text" name="Login"> <br><br> Your favourite colour: <input type="radio" name= Colour value="blue">Blue type= radio name="Colour" value= blue >Blue <input type="radio" name="Colour" value="red">Red <input type="radio" name="Colour" value="green">Green <br><br> Which of these courses you are taking: <br> <input type="checkbox" name="Course" value="elem001">ELEM001 <input type="checkbox" name="Course" value="elem002">ELEM002 <input type="checkbox" name= Course value= elem003 >ELEM003 type= checkbox name="Course" value="elem003">ELEM003 <input type="checkbox" name="Course" value="elem004">ELEM004 <input type="submit" value="Send to Servlet"> </form>
EECS
ProcessBigForm.java (1)
out.println("<table border=1>"); // obtain all the f b i ll h forms parameters f from the request object h bj Enumeration paramNames = req.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); //obtain values for this parameter and check how many there are String [] paramValues = req.getParameterValues(paramName); St i V l tP t V l ( N ) if(paramValues.length == 1) { // a single value String paramVal = req.getParameter(paramName); out.println("<tr><td>" + paramName +"</td><td>" + paramVal + "</td></tr>");
}
EECS
63
ProcessBigForm.java (2)
else { // if several values print a list in the table out.println("<tr><td>" + paramName +"</td><td><ul>"); i l (" d " N " / d d l ") for(int i = 0; i < paramValues.length; i++) out.println( <li> out.println("<li>" + paramValues[i]); } out.println("</ul></td></tr>");
} out.println("</table>");
EECS
64
EECS
65