1 / 43

J2EE Servlets

J2EE Servlets. Ch. 10 (Architecture) Ch. 12 (21 Days). History of Interactive Web. Applets Long download times Code on client machines (maintenance) CGI Custom code to interact with web server Security hole Resource hog for large sites Java Servlets

shasta
Download Presentation

J2EE 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. J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)

  2. History of Interactive Web • Applets • Long download times • Code on client machines (maintenance) • CGI • Custom code to interact with web server • Security hole • Resource hog for large sites • Java Servlets • Standard, easy interface to web server • Security/authentication • Implements sessions

  3. History (cont.) • Early use of Servlets • Simple, easy to use for web applications • MVC all implemented in one big servlet • Very complex • Difficult to maintain • Not scalable • Current state of Servlet use • Smaller is better. • Used only for: • Gathering and validating data input from the user • Coordinating output • Minimal business logic • Web page forwarding

  4. Servlet Features • Tailored to interact with Web Server • Server and platform independent • Efficient and scalable • Container provides additional functionality (i.e., authentication, cookies, etc.)

  5. Interacting with HTML Forms • Get – Request information from web server • Simple http://www.byui.edu/j2ee?Name=Fred+&tel=3565132 • Post – Send data to the server • Submit button, etc. • Data is sent in body of message • Safer than Get

  6. HTML Forms (Cont.) • Put – Place a file on the server • Delete – Remove a web page from server

  7. Class Diagram Servlet Class Diagram

  8. Class Diagram START END Servlet Life Cycle init() doGet(), doPost, … State: Resident ProcessingRequest destroy()

  9. Servlet Sequence Diagram Fig. 12-15

  10. submit doGet/doPost Database webpage Model 1 - Servlets only Model/View/Control WebServer Servlet Generate HTML Data

  11. submit doGet/doPost webpage Performance and Flexibility Issues Servlets in the Enterprise View/Control Model WebServer Servlet EJBEntityBean Input Control Output Data

  12. Get value of form parameters Sent output to web browser Example Servlet publc class HtmlPage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); String telephone = request.getParameter(“tel”); response.setContentType(“text/html”); …. Business logic …. PrintWriter out = response.getWriter(): out.println(“<HTML>”); out.println(“<HEAD><TITLE>First Servlet</TITLE></HEAD>”); out.println(“<BODY>”); out.println(“<H1>Hello “ + name + “, Telephone “ + telephone + “</H1>”); out.println(“</BODY>”); out.println(“</HTML>”); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); } }

  13. submit doGet/doPost <<forward>> webpage Model 2 Architecture View Control Model WebServer Servlet Business Methods<<SessionEJB>> Data Access Objecs<<EntityEJB>> input Data JSPpage output

  14. Web Development Life CycleModel 2 Architecture Servlet JSP Determine and call business function Determine next view Get request Parameters Build view

  15. Web Development Life Cycle protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); try { InitialContext context = new InitialContext(); BusinessRulesRemote businessRules = (BusinessRulesRemote) context.lookup(BusinessRules.REMOTE_JNDI_NAME); Long personId = businessRules.login(username,password); } catch (Exception e) { e.printStackTrace(); } HttpSession session = request.getSession(); session.setAttribute("personid", personId); RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); dispatcher.forward(request, response); } 3. Determine next view 1. Get request parameters 2.Call business function

  16. Web Development Life CycleJSP page <div id="login"> <span class='highlight'>Welcome to Home Town Bank!</span> <br> <a id='logout' href="">Logout</a> </div> 4.Build next view

  17. HttpServletRequest HttpServlet HttpServletResponse doGet(request HttpServletRequest , response:HttpServletResponse) doPost(requestHttpServletRequest, response:HttpServletResponse) doPut(requestHttpServletRequest , response:HttpServletResponse) doDelete(requestHttpServletRequest , response:HttpServletResponse) How to use HTTPServlet Contains Request Info (Input) Handles Response (Output)

  18. RequestResponse Interface Forwarding a Response

  19. RequestResponse Interface Including other Web Components

  20. Deployment of Servlets • All Servlet files zipped together into a web archive (“war”) file • Requires specific directory structure • Deployment Descriptor (WSDL)

  21. Deployment Descriptor <?xml version=“1.0” encoding=“UTF-8:?><!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’ ‘http://java.sun.com/dtd/web-app_2_3.dtd’><web-app> <display-name>A Simple Application</display-name> <servlet> <servlet-name>Verify Data</servlet-name> <servlet-class>VerifyData</servlet-class> <init-param> <param-name>maxValue</param-name> <param-value>25</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Verify Data</servlet-name> <url-pattern>/verifydata</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <error-page> <error-code>404</error-code> <location>/error404.html</location> </error-page></web-app>

  22. Customizing Deployment • Define initialization parameters • Context parameters • Apply to entire web application • Servlet parameters • Apply to a specific servlet

  23. Deployment Descriptor <?xml version=“1.0” encoding=“UTF-8:?><!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’ ‘http://java.sun.com/dtd/web-app_2_3.dtd’><web-app> <display-name>A Simple Application</display-name><context-param> <param-name>location</param-name> <param-value>BYU-Idaho</param-value> <description>Site Location</description> </context-param> <servlet> <servlet-name>Verify Data</servlet-name> <servlet-class>VerifyData</servlet-class><init-param> <param-name>maxValue</param-name> <param-value>25</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Verify Data</servlet-name> <url-pattern>/verifydata</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <error-page> <error-code>404</error-code> <location>/error404.html</location> </error-page></web-app> Context Intialization Parameter Servlet Intialization Parameter

  24. Retrieving Init. Parameters publicvoid init() throws ServletException { super.init(); ServletContext context = this.getServletContext(); String location = context.getInitParameter(“location"); if (maxValue == null) { int maxValue = Integer.parseInt(this.getInitParameter(“maxValue"); } … … }

  25. Handling Errors • HTTP Error Codes • Http Status code – set error code • Error page – set default error page • Send Redirect – redirect to another page • Servlet Exceptions – catch and handle all servlet exceptions

  26. HttpServletResponse public void sendError(int statusCode) public void sendError(int statusCode, String msg)) ….public void sendRedirect(String url); Set HTTP Status Code • Sets the error status code on default error page Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class HtmlPage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); if (name.length() < 1) response.sendError(9001, “Invalid name”); } }

  27. Define output error page for error code Default HTTP Error Page Deployment Descriptor <?xml version=“1.0” encoding=“UTF-8:?><<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’ ‘http://java.sun.com/dtd/web-app_2_3.dtd’><web-app><display-name>A Simple Application</display-name><servlet> <servlet-name>Verify data</servlet-name> <servlet-class>VerifyData</servlet-class> <init-param> <param-name>maxValue</param-name> <param-value>25</param-value> </init-param></servlet> <servlet-mapping> <servlet-name>verifyData</servlet-name> <url-pattern>/verifyData</url-pattern></servlet-mapping><session-config> <session-timeout>30</session-timeout></session-config><error-page> <error-code>9001</error-code> <location>/error9001.html</location></error-page></web-app>

  28. HttpServletResponse public void sendError(int statusCode) public void sendError(int statusCode, String msg)) ….public void sendRedirect(String url); Send Redirect • Redirect to another page to handle error Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class HtmlPage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); if (name.length() < 1) response.sendRedirect(“/Servlets/invalidNamePage”); } }

  29. Servlet Session Management • Hidden fields in form • Visible to client in source (not secure) • Limited amount of data • URL rewritting http://www.byui.edu/j2ee?sessionid=9982345 • Cookies • Store on client browser • May be disabled by some users • Server side session object • Session info stored on Server • Unlimited amount of space • More secure • Automatic management

  30. Cookie HttpServletResponse public void setValue(String value) public String getName()public String getValue()…. … public void addCookie(Cookie c)public Cookie[ ] getCookies() …. Creating Cookies • Implement transactions with Cookies • Store state data in Cookie

  31. Creating a Cookie Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class HtmlPage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try {Cookie cookie = new Cookie(“userAddress”, null); String url = this.getRequextURI(); cookie.addValue(url); response.addCookie(cookie);double quantity = Double.parseDouble(request.getParameter(“quantity”)); double totalQuantity += (Double) session.getAttribute(“totalQuantity”); } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } } }

  32. Retrieving a Cookie publc class HtmlPage extends HttpServlet{String userUrl = new UniqueID(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try {Cookie cookie = null; Cookie[] cookies = response.getCookies(); if (cookies != null) { for (int i=0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().equals(“userAddress”)) { String urlAddress = cookie.getValue(); break; } } } } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } }

  33. HttpSession HttpServletRequest public long getId() public long getLastAccessedTime()public long getCreationTime()public long getMaxInactiveInterval()public Object getAttribute() public boolean isNew() …. … public HttpSession getSession() …. Sessions • Implement transactions with a HttpSession • Retains state of data between page request

  34. Getting a Session Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class HtmlPage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try {HttpSession session = request.getSession(); if (session.isNew()) { Long personId = (Long) session.getAttribute(“personId”); } double quantity = Double.parseDouble(request.getParameter(“quantity”));session.setAttribute(“quantity”); } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } } }

  35. PageHitsFilter Servlet HttpPage Servlet AuthenticateFilterServlet VerifyData Servlet Filter Servlets • Acts as preprocessor to request/response for target servlet …HttpPage …VerifyData

  36. Must implementFilter Interface Must override init. method Must overridedestroy method Filter Servlet Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class PageHits extends HttpServlet implements Filter{ private FilterConfig filterConfig = null;public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy( { this.filterConfig = null; }

  37. Must overridedoFilter method Filter Servlet (cont.) public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig ==null) return; synchronized (this) { Integer counter =(Integer) filterConfig.getServletContext().getAttribute("Counter"); if (counter == null) counter = new Integer(0); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log("Number of hits is " + counter); filterConfig.getServletContext().setAttribute("Counter", counter); } chain.doFilter(req, resp) }

  38. Modify Deployment Descriptor <?xml version=“1.0” encoding=“UTF-8:?><<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’ ‘http://java.sun.com/dtd/web-app_2_3.dtd’><web-app> <display-name>A Simple Application</display-name> <servlet> <servlet-name>VerifyData</servlet-name> <servlet-class>VerifyData</servlet-class> <init-param> <param-name>maxValue</param-name> <param-value>25</param-value> </init-param> </servlet><servlet-mapping> <servlet-name>Verify Data</servlet-name> <url-pattern>/verifyData/</url-pattern> </servlet-mapping><filter> <filter-name>Page Hits</filter-name> <display-name>Page Hits</display-name> <description>Count page hits<description> <filter-class>PageHits</filter-class> </filter> <filter-mapping> <filter-name>PageHits</filter-name><servlet-name>VerifyData</servlet-name> </filter-mapping></web-app>

  39. Listener Servlet • Servlet is automatically executed when some external event occurs

  40. Must implementListner Interface Must override contextInitialized method Must overridecontextInitialized method Create Listener Servlet Import java.io.*;import javax.servlet.*;import javax.servlet.http.*;publc class Listener extends HttpServlet implements ServletContextListener{ private ServletContext context = null;public void contextIntialized(ServletContextEvent event) { context = event.getServerContext(); Integer counter = new Integer(0); context.setAttribute(“Counter”, counter); context.log(“Created Counter”); } public void contextDestroyed(ServletContextEvent event) { event.getServletContext().removeAttribute(“Counter”); }}

  41. Modify Deployment Descriptor <?xml version=“1.0” encoding=“UTF-8:?><<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’ ‘http://java.sun.com/dtd/web-app_2_3.dtd’><web-app><display-name>A Simple Application</display-name> <servlet> <servlet-name>Verify data</servlet-name> <servlet-class>VerifyData</servlet-class> <init-param> <param-name>maxValue</param-name> <param-value>25</param-value> </init-param> </servlet><servlet-mapping> <servlet-name>Verify Data</servlet-name> <url-pattern>/verifyData/</url-pattern> </servlet-mapping> <filter> <filter-name>Page Hits</filter-name> <display-name>Page Hits</display-name> <description>Count page hitsdescription> <filter-class>PageHits</filter-class> </filter> <filter-mapping> <filter-name>PageHits</filter-name> <servlet-name>Verify data</servlet-name> </filter-mapping><listener> < listener-class>Listener</ listener-class> </listener></web-app>

  42. No longer needed Modify Filter Servlet public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {if (filterConfig == null) return; synchronized (this) { Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”); if (counter = null) counter = new Integer(1); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log(“Number of hits is “ + counter); filterConfig.getServletContext().setAttribute(“Counter”, counter); counter); } chain.doFilter(request, response);} }

  43. Modified Filter Servlet public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {if (filterConfig == null) return; synchronized (this) { Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log(“Number of hits is “ + counter); filterConfig.getServletContext().setAttribute(“Counter”, counter); counter); } chain.doFilter(request, response);} }

More Related