900 likes | 1.15k Views
Servlet , JSP. Margus Hanni, Nortal AS. 11.03.2013. Viited varasematele materjalidele…. 2012 – TÜ - Servlets , JSP, Web Containers – Roman Tekhov 2010 – Webmedia - Java EE + containers – Anti Orgla. Kas on asjakohane?.
E N D
Servlet, JSP Margus Hanni, Nortal AS 11.03.2013
Viited varasematele materjalidele… • 2012 – TÜ - Servlets, JSP, WebContainers– Roman Tekhov • 2010 – Webmedia - Java EE + containers – Anti Orgla
Kas on asjakohane? http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
Kas on asjakohane? http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
HelloWorld - C ja JAVA #include <stdio.h> intmain(){ printf("Hello World\n"); return 0; } publicclassHelloWorld{ publicstaticvoidmain(String[]args){ System.out.println("Hello, World"); } }
Kas on asjakohane? • Võrreldes eelmise aastaga on JAVA populaarsus taas kasvanud • Jätkuvalt on JAVA populaarseim keel ning selles osas arvatavasti lähiajal muutusi ei toimu • JAVA on laialdaselt kasutuses erinevate veebilahenduste loomisel
JAVA EE(EnterpriseEdition) • Kogum vahendeid erinevate lahenduste loomiseks: • Veebi rakendused • Veebi teenused • Sõnumivahetus • Andmebaasid • … http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition
JAVA EE • Kogum vahendeid erinevate lahenduste loomiseks: • Veebi rakendused • Veebi teenused • Sõnumivahetus • Andmebaasis • … http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition WebContainer Servlet JSP
WebContainer Manages component life cycles Accepts requests, sends responses Routes requests to applications http://tutorials.jenkov.com/java-servlets/overview.html
Web Containers • ApacheTomcat • JBoss • WebLogic • Jetty • Glassfish • Websphere • …
Web Containers Multiple applications inside one container http://tutorials.jenkov.com/java-servlets/overview.html
Application structure Java source files
Application structure Document root
Application structure Static content
Application structure Configuration, executable code
Application structure Deployment descriptor
Application structure Compiled classes
Application structure Dependencies (JAR-s)
Application structure Java Server Pages
Deployment descriptor (web.xml) Instructs the container how to deal with this application <?xmlversion="1.0" encoding="UTF-8"?> <web-appxmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Deployment descriptor (web.xml) In Servlet API version 3.0 most components of web.xml are replaced by annotations that go directly to Java source code. We will see examples later
Servlets • On JAVA klass, mis töötleb sissetulevat päringut ning tagastab vastuse • Enamasti kasutatakse HTTP päringute ja vastuste töötlemiseks • Servletid töötavad veebikonteineris, mis hoolitseb nende elutsükli ning päringute suunamise eest • javax.servlet.http.HttpServlet – abstraktne klass, mis sisaldab meetodeid doGet ja doPost HTTP päringute töötlemiseks
Servlet example publicclassHelloServletextendsHttpServlet { @Override protectedvoiddoGet(HttpServletRequestreq, HttpServletResponse resp) throwsServletException, IOException { PrintWriterwriter = resp.getWriter(); writer.println("<html><head><title>Hello</title></head><body>"); writer.println("<p>HelloWorld!</p>"); writer.println("<p>Current time: " + new Date() + "</p>"); writer.println("</body></html>"); } }
HttpServlet methods For each HTTP method there is corresponding HttpServlet method doPost doGet doPut …
Servlet Mapping Before Servlet 3.0 in web.xml <servlet> <servlet-name>hello</servlet-name> <servlet-class>example.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
Servlet Mapping In Servlet 3.0 via annotation @WebServlet("/hello") publicclassHelloServletextendsHttpServlet { ...
Servlet life cycle http://tutorials.jenkov.com/java-servlets/servlet-life-cycle.html
Üldine servleti elutsükkel • Kui veebikonteineris puudub Servleti instants • Laetakse Servleti klass • Luuakse isend • Initsialiseeritakse (init meetod) • Iga päringu jaoks kutsutakse välja servicemeetod • Servleti kustutamisel kutsutakse välja destroy meetod
Sessions HTTP is a stateless protocol, but we often need the server to remember us between requests There are some ways Cookies URL rewriting
Java HttpSession • HttpSession is a common interface for accessing session context • Java Servlet API abstract away the details of how the session is maintained
Java HttpSession http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html
HttpSession example HttpSessionsession = req.getSession(); intvisit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit);
HttpSession example HttpSessionsession = req.getSession(); intvisit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Either create a new session or get existing
HttpSession example HttpSessionsession = req.getSession(); intvisit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Check if the session is fresh or not
HttpSession example HttpSessionsession = req.getSession(); intvisit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Retrieveattribute
HttpSession example HttpSessionsession = req.getSession(); intvisit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Update attribute
HttpServletRequest Contains request information Also can be used to store attributes request.setAttribute(“key", value); request.getAttribute(“key”);
HttpServletRequest: parameters request.getParameterNames(); Enumeration<String> String value = request.getParameter("name");
HttpServletRequest: meta data request.getMethod(); “GET”, “POST”, … request.getRemoteAddr(); Remote client’s IP request.getServletPath(); “/path/to/servlet” …
HttpServletRequest: headers request.getHeaderNames(); Enumeration<String> request.getHeader("User-Agent"); “Mozilla/5.0 (X11; Linux x86_64) …”
HttpServletRequest: cookies Cookie[] cookies = request.getCookies(); cookie.getName(); cookie.getValue(); cookie.setValue(“new value”);
HttpServletResponse Allows to set response information response.setHeader("Content-Type", "text/html"); response.addCookie(newCookie("name", "value"));
HttpServletResponse: content response.getWriter().println("..."); Write text response.getOutputStream().write(...); Write binary
Problem with servlets Writing HTML in Java is hideous PrintWriterwriter = resp.getWriter(); writer.println("<html><head><title>Hello</title></head><body>"); writer.println("<p>HelloWorld!</p>"); writer.println("<p>Current time: " + new Date() + "</p>"); writer.println("</body></html>");
Java Server Pages (JSP) • Write standard markup • Add dynamic scripting elements • Add Java code