MVC for Servlets 23-Feb-19.

Slides:



Advertisements
Similar presentations
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
Advertisements

10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
27-Jun-15 Directories and DDs. 2 Web apps A web application is basically a web site that: “Knows who you are”--it doesn’t just give you static pages,
Servlets CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Chapter 5 Being a Web App. Very few servlet or JSP stands alone Many times in our application, different servlets or JSPs need to share information 
CS-4220 Dr. Mark L. Hornick1 Servlet configuration and deployment.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Java Server Pages (JSP)
CSCI 6962: Server-side Design and Programming Java Server Faces Scoping and Session Handling.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
OOSSE Week 8 JSP models Format of lecture: Assignment context JSP models JSPs calling other JSPs i.e. breaking up work Parameter passing JSPs with Add.
Servlets.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
MVC for Servlets 26-Apr-17.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Java Servlets References: Karen Anewalt, Mary Washington College.
JSP Implicit Objects CS 422 Dick Steflik.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Java Server Pages.
Java Servlets.
Pre assessment Questions
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Servlet API and Lifecycle
Intro to PHP & Variables
Sessions.
Server Side Programming: Java Servlets
Chapter 26 Servlets.
Servlets.
All You Ever Wanted To Know About Servlets
Handling State in Web Applications
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
CS3220 Web and Internet Programming Introduction to Java Servlets
MVC for Servlets 29-Apr-19.
Directories and DDs 25-Apr-19.
Pre-assessment Questions
MVC for Servlets 5-Jul-19.
Directories and DDs 21-Jul-19.
Directories and DDs 14-Sep-19.
Presentation transcript:

MVC for Servlets 23-Feb-19

MVC One of the most common Design Patterns is Model-View-Controller (MVC) The model does all the computational work It is input/output free All communication with the model is via methods The controller tells the model what to do User input goes to the controller The view shows results; it is a “window” into the model The view can get results from the controller, or The view can get results directly from the model

Advantages of MVC One advantage is separation of concerns Computation is not intermixed with I/O Consequently, code is cleaner and easier to understand Another advantage is flexibility The GUI (if one is used) can be completely revamped without touching the model in any way Another big advantage is reusability The same model used for a servlet can equally well be used for an application or an applet (or by another process) MVC is widely used and recommended

MVC for servlets The model, as usual, does all the computational work, and no I/O The model can consist of multiple classes The servlet class (the one that extends HttpServlet) acts as the controller The servlet gives any relevant information from the user request to the model The servlet takes the results and passes them on to the view The view—that is, the HTML page that is returned to the user—is frequently created by JSP

Web applications A web application typically consists of: Some (Java) class, acting as the controller, that extends HttpServlet The model code (also Java) The view code (ultimately Java, but we write it as JSP) Plus, of course, the web.xml file All these parts need to communicate with one another That’s what the rest of this lecture is (mostly) about

web.xml  servlet 23-Feb-19

Servlet life-cycle methods public void init() Called after the servlet is constructed but before the servlet is placed into service As the name implies, a good place to do initializations public void service(ServletRequest request, ServletResponse response) Called when a servlet request is made The HttpServlet service method will dispatch the request to doGet, doPost, or one of the other service methods public void destroy() Called when a servlet is terminated Can be used to clean up any resources (files, databases, threads, etc.)

ServletConfig You can override public void init() Servlet has the methods: public ServletConfig getServletConfig() You will probably use this if you override init() public String getServletInfo() By default, returns an empty string; override to make it useful The main purpose of ServletConfig is to provide initialization information to the servlet ServletConfig has these methods: public java.lang.String getServletName() public ServletContext getServletContext() public Enumeration getInitParameterNames() public String getInitParameter(String name) Our interest will be in getting initialization parameters

Servlet init parameters Where does a servlet get its initialization information? From the web.xml file, of course! Inside <servlet>: <init-param> <param-name>myName</param-name> <param-value>myValue</param-value> </init-param> In the servlet code: String myValue = getServletConfig().getInitParameter("myName");

web.xml  entire web application 23-Feb-19

Multiple servlets A web application can consist of multiple servlets We just saw how to send configuration information to a single servlet Context init parameters can send configuration information to all servlets in a web application Not inside a particular <servlet> tag: <context-param> <param-name>myName</param-name> <param-value>myValue</param-value> </context-param> In any servlet: String myValue = getServletContext().getInitParameter("myName");

Servlet vs. context init parameters Servlet init parameters are: Defined within a <servlet> tag Written within an <init-param> tag Retrieved from a ServletConfig object, which you get by calling getServletConfig() Read from the ServletConfig object by calling getInitParameter(name) Context init parameters are: Defined outside all <servlet> tags Written within a <context-param> tag Retrieved from a ServletContext object, which you get by calling getServletContext() Read from the ServletContext object by calling getInitParameter(name)

Public ServletContext methods String getInitParameter(String name) Enumeration getInitParameterNames() Object getAttribute(String name) Enumeration getAttributeNames() void setAttribute(String name, Object object) void removeAttribute(String name) String getRealPath(String path) RequestDispatcher getRequestDispatcher(String path)

servlet  JSP 23-Feb-19

The ServletRequest object You’ve seen these methods of the ServletRequest object: public Enumeration getParameterNames() public String getParameter(String name) public String[] getParameterValues(String name) ServletRequest also has these methods: public Enumeration getAttributeNames() public Object getAttribute(String name) public void setAttribute(String name, Object object) You can use attributes to send information to the JSP

Dispatching to the JSP request.setAttribute(name, object) Notice that we put the information on the request RequestDispatcher view = request.getRequestDispatcher("result.jsp"); We ask the request object for a dispatcher We supply, as a String, a path to the JSP file If the path begins with a slash, it is relative to the current context root Otherwise, it is relative to the servlet location view.forward(request, response); Having added the result information to the HttpRequest object, we forward the whole thing to the JSP The JSP does the rest—it will send out the HTML page

Aside: redirect vs. forward The previous slide showed how a servlet could forward a request to JSP (or to another servlet) This is all done on the server side response.sendRedirect(URL) sends a response back to the browser that says, in effect, “I can’t handle this request; you should go to this URL instead.” You cannot use this method if you have already written something to the response The URL can be relative to the location of this servlet

Attributes 23-Feb-19

Parameters are not attributes You can get parameters from the Deployment Descriptor: getServletConfig().getInitParameter(name); getServletContext().getInitParameter(name); You cannot set these parameters You can get request parameters request.getParameter(String name) Parameter values are always Strings Attribute values are always Objects When you get an attribute, you have to cast it to the type you want

Attribute scopes Servlets can access three scopes: Application scope All servlets in the web application have access Attributes are stored in the ServletContext object Available for the lifetime of the servlet Session scope Available to servlets that have access to this specific session Attributes are stored in the HttpSession object Available for the life of the session Request scope Available to servlets that have access to this specific request Attributes are stored in the ServletRequest object Available for the life of the request (until your doGet or doPost method completes)

Attribute methods ServletContext objects, ServletRequest objects, and HttpSession objects all have the following methods: Object getAttribute(String name) void setAttribute(String name, Object object) void removeAttribute(String name) Enumeration getAttributeNames()

Thread safety Thread problems can occur when: One Thread is writing to (modifying) an object at the same time another Thread is reading it Two (or more) Threads are trying to write to the same object at the same time Thread problems cannot (in general) be detected by the Java runtime system Instead, thread problems cause random, mysterious, non-replicable corruption of data There are simple steps that you can take to avoid many threading problems However, threading is very error-prone and can be extremely difficult to ensure that you have it right

Thread safety in servlets Tomcat starts a new Thread for every new request Each request, and therefore each Thread, has its own request and response objects Therefore, these are inherently Thread-safe Local variables (including parameters) of your service methods are also thread-safe Instance variables are not thread-safe You don’t have multiple servlet objects—you have multiple Threads using the same servlet object Application (context) scope is shared by all servlets Therefore, context attributes are inherently Thread-unsafe Session attributes are not completely Thread-safe It is possible to have multiple simultaneous requests from the same session

Thread safety in class assignments In reality, the servlets you write for this course are not going to service thousands of requests per second You (and my TA) will enter a few requests manually, with billions of nanoseconds in between You are not going to have threading problems However... I’m trying to teach “real world” programming Therefore, you have to pretend that thread safety is a real issue in your programming assignments If I had lots of spare time (which I don’t!), I could write a program to send your servlet thousands of requests per second Even if I did that, my program could not reliably catch problems Bottom line: Try your best to make your servlets thread-safe, even though we can’t test them for thread safety

Protecting context attributes To protect context attributes, synchronize on the ServletContext object Example (from Head First Servlets & JSP): synchronized(getServletContext()) { getServletContext().setAttribute("foo", "22"); getServletContext().setAttribute("bar", "42"); out.println(getServletContext().getAttribute("foo")); out.println(getServletContext().getAttribute("bar")); } This will protect you from any other code that also synchronizes on the ServletContext It will not protect you from code that doesn’t so synchronize But this is the best we can do

Protecting session attributes To protect session attributes, synchronize on the HttpSession object Example (from Head First Servlets & JSP): HttpSession session = request.getSession(); synchronized(session) { session.setAttribute("foo", "22"); session.setAttribute("bar", "42"); out.println(session.getAttribute("foo")); out.println(session.getAttribute("bar")); } This will protect you from any other code that also synchronizes on the HttpSession

Getting init parameters in JSP You can get servlet and context init parameters in your JSP Step 1: Specify in your DD that you want them: <servlet> <servlet-name>SomeServletName</servlet-name> <jsp-file>/UseServletInit.jsp</jsp-file> <init-param> ... </init-param> <init-param> ... </init-param> ... </servlet> Step 2: Override jspInit() (must be done in a JSP declaration): <%! public void jspInit() { // use getServletConfig() and getServletContext() as usual } %>

PageContext In JSP, pageContext is an implicit object (like request and response) of type PageContext PageContext has these methods (among others): Object getAttribute(String name) // uses page scope Object getAttribute(String name, int scope) Enumeration getAttributeNamesInScope(int scope) Object findAttribute(String name) Searches in the order: page context, request scope, session scope, application scope void setAttribute(String name, Object value) void setAttribute(String name, Object value, int scope) Where scope can be one of PageContext.APPLICATION_SCOPE, PageContext.PAGE_SCOPE, PageContext.REQUEST_SCOPE, or PageContext.SESSION_SCOPE So you can access a lot of information from a PageContext object!

The End