330 likes | 844 Views
Servlets. CEN 4010. Servlets overview. Servlet Technology Handling requests Session tracking Handling Cookies JDBC Servlet. Webserver . web site files html files: text, multi-media and links Common Gateway Interface (CGI): cgi scripts: sh, csh, Perl, … Servlets:
E N D
Servlets CEN 4010
Servlets overview • Servlet Technology • Handling requests • Session tracking • Handling Cookies • JDBC Servlet
Webserver • web site files • html files: text, multi-media and links • Common Gateway Interface (CGI): • cgi scripts: sh, csh, Perl, … • Servlets: • Java program that runs on webserver • JavaServer pages (JSP): • Contains html and Java • Compiled into a servlet and run on webserver
Servlet • Supports request/response model • client send request • server responds (with html page) • Different types of servlets • GenericServlet • not protocol specific • HttpServlet • Serves http requests
Servlet tasks • process html forms • middle-tier processing • connect to sources behind firewall (e.g. DB) • maintain session information between requests • serve as concentration point for multiple clients
Servlet runs on webserver • requested via URL by client • requires special webserver • Tomcat, IBM application server, JRun, Oracle … • can start with webserver • permanent: if startup effort is high • can be started on client request • temporary: if rarely used • servlet is unaware of when it was started
Basic modes of operation • Multi threaded • Single servlet instance runs in many threads • Servlet fields shared • Must consider field contention • Single threaded • Multiple instances, each in one thread • Servlet fields are not shared
Servlet interfaces and classes • Java Servlet packages • javax.servlet • javax.servlet.http • Part of J2EE • to compile include into CLASSPATH (tomcat)... common\lib\servlet-api.jar
HttpServletservice method invoked for “get” and “post” method in html form
Servlet example: HelloWorld.java package mypackage; 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><head><title>Hello</title></head>”); out.println(“<body>”); out.println("Hello World“); out.println(“</body></html>”); } }
Make the servlet known as web application: web.xml <web-app> <display-name>HelloWorld example</display-name> <description>Welcome to HelloWorld</description> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>mypackage.HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
html example: hello.html <html> <head> <title>Hello World Servlet Example</title> <body> <form action=“http://localhost:8080/HelloExample/hello” method=“get”> <input type=“submit”> </form> </body> </html>
Servlet deployment on Tomcat • Create directory ...\webapps\HelloExample • Copy hello.html into this directory as index.html • Create subdirectory WEB-INF • Create subdirectory WEB-INF\classes • Compile HelloWorld.java to WEB-INF\classes\mypackage\HelloWorld.class • Copy web.xml into directory: WEB-INF • Open “http://localhost:8080/HelloExample”
Process Form parameters • html form defines fields with • name • type • value(s) • received by servlet via request parameter • HttpServletRequest class defines helper methods
Helper methods • getParameter(“name”) • Returns string (maybe empty) or null if parameter does not exist • getParameterValues(“name”) • Returns array of strings • getParameterNames() • Returns enumeration of parameter names
html example <html> <body> <head> <title>Request Parameters Example</title> </head> <h3>Request Parameters Example</h3> Please enter <p><form action="params" method=POST> First Name: <input type=text size=20 name=firstname> <br> Last Name: <input type=text size=20 name=lastname> <br> <input type=submit> </form> </body> </html>
doPost method String first = request.getParameter("firstname"); String last = request.getParameter("lastname"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Answer</title></head>"); out.println("<body>Welcome " + first + " " + last); out.println("</body></html>");
Keep track of session • http is a stateless protocol • but there is need to maintain session information • username, password • shopping cart • … • possible: use hidden field(s) • better: HttpSession
Keep track of session • session can remember values for attributes across servlet invocations • methods: • session = request.getSession(true); • session.setAttribute(“name”, object); • session.getAttribute(“name”);
getSession session = request.getSession(true); • retrieves current session from request • “true” parameter causes new session to be created if it does not exist • session remains alive until: • it times out (reaches time maximum) • explicit cancellation
Attributes • getAttribute(“name”) • setAttribute(“name”, value) • value can be any object • removeAttribute(“name”) • getAttributeNames()
HttpSession methods • getID() • isNew() • getCreationTime() • getLastAccessedTime() • invalidate() • setMaxInactiveInterval() • getMaxInactiveInterval()
SessionServlet: doPost (1/3) HttpSession session = request.getSession(true); String heading; if (session.isNew()) { heading = "Welcome, Newcomer"; } else { heading = "Hello Again"; }
SessionServlet: doPost (2/3) Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount != null) { accessCount = new Integer(accessCount.intValue() + 1); } else { accessCount = new Integer(0); } session.setAttribute("accessCount", accessCount);
SessionServlet: doPost (3/3) response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Answer</title></head>"); out.println("<body> " + heading + "<br>"); out.println("Number of previous accesses " + accessCount ); out.println("</body></html>");
Handle Cookies • allow to store information in the browser • can be retrieved by servlet • 2 types • temporary cookies • lasts as long as the browser instance • permanent cookies • must have expiration date • can be deleted • Note: browsers can disable cookies
To establish a Cookie • create instance of class Cookie Cookie mine = new Cookie(“name”, “value”); • permanent has max age mine.setMaxAge(seconds); • can have domain and path mine.setDomain(“.aul.fiu.edu”); mine.setPath(“/catalog”);
To access Cookies • through request parameter Cookie all[] = request.getCookies(); • find your cookie for (int i=0; i<all.length; i++) { out.println(“Cookie name: “ + all[i].getName()); out.println(“ value: “ + all[i].getValue()); }
To save Cookie • through response header response.addCookie(singleCookie); • Example: Cookie mine = new Cookie(“user”, “ege”); mine.setMaxAge(60 * 60 * 24 * 365); response.addCookie(mine);
Access database • servlet may access database using JDBC • load driver • get connection • formulate statement • execute statement • process result set
Example: database access Class.forName("com.sybase.jdbc.SybDriver"); conn = DriverManager.getConnection("jdbc:sybase:Tds:ocelot.aul.fiu.edu:7100", “student", “student"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Customers</title></head><body>"); String s1 = "select * from Customers;"; Statement s = conn.createStatement(); ResultSet result = s.executeQuery(s1); out.println("<table border=1><tr><th>ID<th>name<th>city<th>street</tr>"); while (result.next()) { out.println("<tr><td>" + result.getInt(1)); out.println("<td>" + result.getString(2)); out.println("<td>" + result.getString(3)); out.println("<td>" + result.getString(4) + "</tr>"); } out.println("</table></body></html>");
Performance considerations • new connection is created for every request to servlet • other choices • place connection into session