"> ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Margus Hanni, Nortal AS Servlet, JSP 30.03.2015. Millest räägime JAVA Web Container Servlet JSP.

Similar presentations


Presentation on theme: "Margus Hanni, Nortal AS Servlet, JSP 30.03.2015. Millest räägime JAVA Web Container Servlet JSP."— Presentation transcript:

1 Margus Hanni, Nortal AS Servlet, JSP 30.03.2015

2 Millest räägime JAVA Web Container Servlet JSP

3 Hello World #include int main() { printf("Hello World\n"); return 0; } public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } Hello World '; ?> 1 2 34

4 JAVA JAVA?

5 JAVA - primary goals Five primary goals in the creation of the Java language: 1.It should use the object-oriented programming methodology. 2.It should allow the same program to be executed on multiple operating systems. 3.It should contain built-in support for using computer networks. 4.It should be designed to execute code from remote sources securely. 5.It should be easy to use by selecting what was considered the good parts of other object-oriented languages. http://www.freejavaguide.com/history.html

6 JAVA - Versions Major release versions of Java, along with their release dates: JDK 1.0 (January 21, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) J2SE 5.0 (September 30, 2004) Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011) Java SE 8 (March 18, 2014) http://en.wikipedia.org/wiki/Java_%28programming_language%29

7 JAVA EE (Enterprise Edition) Kogum vahendeid (API) erinevate lahenduste loomiseks: Veebi rakendused Veebi teenused Sõnumivahetus Andmebaasid … http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition

8 API - application programming interface Is a set of routines, protocols and tools for building software applications. Specifies „ground rules“ Specifies how software components should interact with each ohter A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together http://en.wikipedia.org/wiki/Application_programming_interface

9 JAVA EE Kogum vahendeid erinevate lahenduste loomiseks: Veebi rakendused Veebi teenused Sõnumivahetus Andmebaasis … http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition Web Container Servlet JSP Web Container Servlet JSP

10 Web Container Manages component life cycles Routes requests to applications Accepts requests, sends responses http://tutorials.jenkov.com/java-servlets/overview.html

11 Web Containers Apache Tomcat JBoss WebLogic Jetty Glassfish Websphere …

12 Web Containers Multiple applications inside one container http://tutorials.jenkov.com/java-servlets/overview.html

13 Application structure

14 Java source files

15 Application structure Document root

16 Application structure 16 Static content

17 Application structure Configuration, executable code

18 Application structure Deployment descriptor

19 Application structure Compiled classes

20 Application structure Dependencies (JAR-s)

21 Application structure Java Server Pages

22 Deployment descriptor (web.xml) Instructs the container how to deal with this application <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> index.html

23 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

24 Servlets On JAVA klass, mis töötleb sissetulevat päringut ning tagastab vastuse Enamasti kasutatakse HTTP päringu töötlemiseks ja tulemuse saatmiseks Servletid töötavad veebikonteineris, mis hoolitseb nende elutsükli ning päringute suunamise eest javax.servlet.http.HttpServlet – abstraktne klass, mis sisaldab meetodeid doXXX HTTP päringute töötlemiseks

25 Servlet example public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.println(" Hello "); writer.println(" Hello World! "); writer.println(" Current time: " + new Date() + " "); writer.println(" "); } Mis on tulemuseks?

26 Servleti töö

27 HttpServlet methods For each HTTP method there is corresponding HttpServlet method doPost doGet doPut …

28 Servlet Mapping Before Servlet 3.0 in web.xml hello example.HelloServlet hello /hello Example

29 Servlet Mapping In Servlet 3.0 via annotation @WebServlet("/hello") public class HelloServlet extends HttpServlet {...

30 Servlet life cycle http://tutorials.jenkov.com/java-servlets/servlet-life-cycle.html

31 Üldine servleti elutsükkel Kui veebikonteineris puudub Servleti instants Laetakse Servleti klass Luuakse isend Initsialiseeritakse (init meetod) Iga päringu jaoks kutsutakse välja service meetod. Servleti kustutamisel kutsutakse välja destroy meetod Kus on päringumeetodid?

32 Sessions HTTP is a stateless protocol, but we often need the server to remember us between requests. There are some ways: Cookies URL rewriting

33 Java HttpSession HttpSession is a common interface for accessing session context Actual implementation is provided by a Web Container

34 Java HttpSession http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html

35 HttpSession example HttpSession session = req.getSession(); int visit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit);

36 HttpSession example HttpSession session = req.getSession(); int visit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Either create a new session or get existing

37 HttpSession example HttpSession session = req.getSession(); int visit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Check if the session is fresh or not

38 HttpSession example HttpSession session = req.getSession(); int visit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Retrieve attribute

39 HttpSession example HttpSession session = req.getSession(); int visit; if (session.isNew()) { visit = 0; } else { visit = (Integer) session.getAttribute("visit"); } session.setAttribute("visit", ++visit); Update attribute

40 HttpServletRequest - Attribute Contains request information Also can be used to store attributes request.setAttribute(“key", value); request.getAttribute(“key”);

41 HttpServletRequest: Parameter request.getParameterNames(); Enumeration String value = request.getParameter("name");

42 HttpServletRequest: Parameter vs Attribute Object value = request.getAttribute(“key”); String value = request.getParameter("name");

43 HttpServletRequest: meta data request.getMethod(); “GET”, “POST”, … request.getRemoteAddr(); Remote client’s IP request.getServletPath(); “/path/to/servlet” …

44 HttpServletRequest: headers request.getHeaderNames(); Enumeration request.getHeader("User-Agent"); “Mozilla/5.0 (X11; Linux x86_64) …”

45 Request Headers Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encodinggzip, deflate Accept-Languageet,et-ee;q=0.8,en-us;q=0.5,en;q=0.3 Connectionkeep-alive Cookie JSESSIONID=C687CC4E2B25B8A27DAB4A5F30980583; __utma=111872281.1173964669.1316410792.1318315398.13 38294258.52; oracle.uix=0^^GMT+3:00^p Hostlocalhost:8080 User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0

46 Request Headers: www.neti.ee

47 Cookie Small piece of information (some ID, parameter, preference etc..) Stored in browser Usually sent by a server Client sends only name-value pair JSESSIONID = C687CC4E2B25B8A27DAB4A5F3098058 language=en Cookie parameters: Name Value Expires Path Domain Security (can be sent over ssh only) HttpOnly

48 HttpServletRequest: cookies Cookie[] cookies = request.getCookies(); cookie.getName(); cookie.getValue(); cookie.setValue(“new value”);

49 Cookie: www.postimees.ee

50 HttpServletResponse Allows to set response information response.setHeader("Content-Type", "text/html"); response.addCookie(new Cookie("name", "value"));

51 Response Headers Content-Languageet Content-Typetext/html;charset=UTF-8 DateMon, 11 Mar 2013 06:48:54 GMT ServerApache-Coyote/1.1 Transfer-Encodingchunked

52 Response Headers: www.neti.ee

53 Request Response: www.neti.ee

54 HttpServletResponse: content response.getWriter().println("..."); Write text response.getOutputStream().write(...); Write binary

55 Problem with servlets Writing HTML in Java is hideous PrintWriter writer = resp.getWriter(); writer.println(" Hello "); writer.println(" Hello World! "); writer.println(" Current time: " + new Date() + " "); writer.println(" ");

56 Java Server Pages (JSP) Write HTML standard markup language Add dynamic scripting elements Add Java code

57 JSP example war/WEB-INF/jsp/hello.jsp Hello Hello World! Current time:

58 JSP mapping In web.xml hello2 /WEB-INF/jsp/hello.jsp hello2 /hello2

59 JSP life cycle http://www.jeggu.com/2010/10/jsp-life-cycle.html http://www.tutorialspoint.com/jsp/jsp_life_cycle.htm

60 package org.apache.jsp.WEB_002dINF.jsp.document; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.Date; public final class testdokument_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map _jspx_dependants; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map getDependants() { return _jspx_dependants; } public void _jspInit() { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write(" Current time: "); out.print( new Date() ); out.write(" "); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); }

61 Dynamic content Expression Current time: Scriptlet Current time:

62 Dynamic content Declaration <%! private Date currentDate(){ return new Date(); } %> Current time:

63 JSP Eeldefineeritud muutujad request- HttpServletRequest response – HttpServletResponse out – Writer session – HttpSession application – ServletContext pageContext – PageContext

64 JSP Märgendid jsp:include Veebipäring antakse ajutiselt üle teisele JSP lehele. jsp:forward Veebpäring antakse jäädavalt üle teisele JSP lehele. jsp:getProperty Loeb JavaBeani muutuja väärtuse. jsp:setProperty Määrab JavaBeani muutuja väärtuse. jsp:useBean Loob uue või taaskasutab JSP lehele kättesaadavat JavaBeani.

65 Expression Language (EL) Easy way to access JavaBeans in different scopes Rea summa: ${rida.summa * rida.kogus}

66 Basic Operators in EL OperatorDescription.Access a bean property or Map entry []Access an array or List element ( )Group a subexpression to change the evaluation order +Addition -Subtraction or negation of a value *Multiplication / or divDivision % or modModulo (remainder) == or eqTest for equality != or neTest for inequality < or ltTest for less than > or gtTest for greater than <= or leTest for less than or equal >= or gtTest for greater than or equal && or andTest for logical AND || or orTest for logical OR ! or notUnary Boolean complement emptyTest for empty variable values http://www.tutorialspoint.com/jsp/jsp_expression_language.htm

67 Scopes Many objects allow you to store attributes ServletRequest.setAttribute HttpSession.setAttribute ServletContext.setAttribute

68 Andmete skoobid ServletContext – veebikontekst, üks ühe rakenduse ja JVM-i kohta Sessioon – üks iga kasutajasessiooni kohta (erinev lehitseja = erinev sessioon) Request – konkreetse päringu skoop Andmete kirjutamiseks/lugemiseks on meetodid setAttribute/getAttribute

69 Scopes http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html

70 Scopes <% application.setAttribute("subject", "Web information systems"); session.setAttribute("topic", "Servlets"); request.setAttribute("lector", "Roman"); pageContext.setAttribute("lector", "Roman"); %> Subject: ${subject} Topic: ${topic} Lector: ${lector} Väljund: Subject: Web information systems Topic: Servlets Lector: Roman

71 Scopes <% application.setAttribute("subject", "Web information systems"); session.setAttribute("topic", "Servlets"); request.setAttribute("lector", "Roman"); pageContext.setAttribute("lector", "Roman"); pageContext.setAttribute("subject", "Meie uus teema"); application.setAttribute("subject", "Meie järgmine teema"); %> Subject: ${subject} Topic: ${topic} Lector: ${lector} Mis on väljundiks?

72 Scopes <% application.setAttribute("subject", "Web information systems"); session.setAttribute("topic", "Servlets"); request.setAttribute("lector", "Roman"); pageContext.setAttribute("lector", "Roman"); pageContext.setAttribute("subject", "Meie uus teema"); application.setAttribute("subject", "Meie järgmine teema"); %> Subject: ${subject} Topic: ${topic} Lector: ${lector} Subject: Meie uus teema Topic: Servlets Lector: Roman

73 Scopes <% application.setAttribute("subject", "Web information systems"); session.setAttribute("topic", "Servlets"); request.setAttribute("lector", "Roman"); pageContext.setAttribute("lector", "Roman"); %> Subject: ${subject} Topic: ${topic} Lector: ${lector} Less visible

74 JavaBeans public class Person implements Serializable { private String name; public Person() {} public String getName() { return name; } public void setName(String name) { this.name = name; } Implements Serializable Public default constructor getX and setX methods for each property X

75 JavaBeans in EL Person person = new Person(); person.setName("Roman"); request.setAttribute("person", person); Person: ${person.name}

76 Java Standard Tag Library (JSTL) Set of standard tools for JSP <% List lectors = Arrays.asList("Siim", "Roman", "Margus"); pageContext.setAttribute("lectors", lectors); %> Name: ${lector} (guest)

77 Problem with JSP Writing Java in JSP is hideous Current time: Example

78 Servlet + JSP JSP on puhtam Kihid on eraldatud Korduvkasutatavus Kuid kas saab paremini?

79 Model-View-Controller (MVC) http://java.sun.com/blueprints/patterns/MVC-detailed.html

80 Servlet controller, JSP view protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("currentDate", new Date()); req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req, resp); } Model data Controller gets invoked

81 Servlet controller, JSP view protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("currentDate", new Date()); req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req, resp); } Select and invoke view Controller gets invoked

82 Servlet controller, JSP view WEB-INF/jsp/hello.jsp... Current time: ${currentDate} View uses the data from model

83 Filters Allows you to do something before, after or instead of servlet invocation. http://docs.oracle.com/javaee/5/tutorial/doc/bnagb.html Filter chain

84 Filter example public class LoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long start = System.currentTimeMillis(); chain.doFilter(request, response); long end = System.currentTimeMillis(); System.out.println("Time spent: " + (end - start)); }

85 Filter example public class LoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long start = System.currentTimeMillis(); chain.doFilter(request, response); long end = System.currentTimeMillis(); System.out.println("Time spent: " + (end - start)); } Invoke next filter in chain or the servlet if this was the last filter

86 Filter declaration Before Servlet 3.0 in web.xml loggingFilter example.LoggingFilter hello /*

87 Filter declaration In Servlet 3.0 via annotation @WebFilter("/*") public class LoggingFilter implements Filter {...

88 Life cycle event listeners javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.ServletRequestListener javax.servlet.ServletRequestAttributeListener javax.servlet.http.HttpSessionListener javax.servlet.http.HttpSessionAttributeListener

89 Listener example public class LoggingRequestListener implements ServletRequestListener { @Override public void requestInitialized(ServletRequestEvent event) { System.out.println("Received request from " + event.getServletRequest().getRemoteAddr()); } @Override public void requestDestroyed(ServletRequestEvent event) {} }

90 Listener declaration Before Servlet 3.0 in web.xml example.LoggingRequestListener

91 Listener declaration In Servlet 3.0 via annotation @WebListener public class LoggingRequestListener implements ServletRequestListener {...

92 Should I bother? There are a lot of fancy Java web frameworks that simplify application building. Should I still learn these basic technologies, will I ever use them?

93 Should I bother? You are still going to deploy your application to a web container. Most traditional frameworks use JSP as the view technology.

94 Should I bother? http://en.wikipedia.org/wiki/Java_servlet

95 What about servlets? Most frameworks are based on the Servlet API You will probably still encounter things like HttpSession, HttpServletRequest etc inside your code. You might want to write filters and listeners. You probably won’t write much servlets. But sometimes they can still be handy for simple tasks. AngularJS and REST (Representational State Transfer)

96 Sources of wisdom Tutorial http://docs.oracle.com/javaee/7/tutorial/ http://www.coreservlets.com/java-8-tutorial/ API http://docs.oracle.com/javaee/7/api/


Download ppt "Margus Hanni, Nortal AS Servlet, JSP 30.03.2015. Millest räägime JAVA Web Container Servlet JSP."

Similar presentations


Ads by Google