1 / 33

Servlets

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:

alta
Download Presentation

Servlets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Servlets CEN 4010

  2. Servlets overview • Servlet Technology • Handling requests • Session tracking • Handling Cookies • JDBC Servlet

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. HttpServletservice method invoked for “get” and “post” method in html form

  10. HttpServlet class

  11. 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>”); } }

  12. 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>

  13. 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>

  14. 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”

  15. Process Form parameters • html form defines fields with • name • type • value(s) • received by servlet via request parameter • HttpServletRequest class defines helper methods

  16. 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

  17. 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>

  18. 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>");

  19. 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

  20. 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”);

  21. 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

  22. Attributes • getAttribute(“name”) • setAttribute(“name”, value) • value can be any object • removeAttribute(“name”) • getAttributeNames()

  23. HttpSession methods • getID() • isNew() • getCreationTime() • getLastAccessedTime() • invalidate() • setMaxInactiveInterval() • getMaxInactiveInterval()

  24. SessionServlet: doPost (1/3) HttpSession session = request.getSession(true); String heading; if (session.isNew()) { heading = "Welcome, Newcomer"; } else { heading = "Hello Again"; }

  25. 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);

  26. 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>");

  27. 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

  28. 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”);

  29. 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()); }

  30. 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);

  31. Access database • servlet may access database using JDBC • load driver • get connection • formulate statement • execute statement • process result set

  32. 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>");

  33. Performance considerations • new connection is created for every request to servlet • other choices • place connection into session

More Related