MVC for Servlets MVC n n One of

  • Slides: 29
Download presentation
MVC for Servlets

MVC for Servlets

MVC n n One of the most common Design Patterns is Model. View-Controller (MVC)

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

Advantages of MVC n One advantage is separation of concerns n n n Another

Advantages of MVC n One advantage is separation of concerns n n n Another advantage is flexibility n n The GUI (if one is used) can be completely revamped without touching the model in any way Another big advantage is reusability n n Computation is not intermixed with I/O Consequently, code is cleaner and easier to understand 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 3

MVC for servlets n The model, as usual, does all the computational work, and

MVC for servlets n The model, as usual, does all the computational work, and no I/O n n The servlet class (the one that extends Http. Servlet) acts as the controller n n n The model can consist of multiple classes 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 4

Web applications n A web application typically consists of: n n n Some (Java)

Web applications n A web application typically consists of: n n n Some (Java) class, acting as the controller, that extends Http. Servlet 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 n That’s what the rest of this lecture is (mostly) about 5

web. xml servlet

web. xml servlet

Servlet life-cycle methods n public void init() n n n public void service(Servlet. Request

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

Servlet. Config n You can override public void init() n Servlet has the methods:

Servlet. Config n You can override public void init() n Servlet has the methods: n n n public Servlet. Config get. Servlet. Config() n You will probably use this if you override init() public String get. Servlet. Info() n By default, returns an empty string; override to make it useful The main purpose of Servlet. Config is to provide initialization information to the servlet n Servlet. Config has these methods: n n n public java. lang. String get. Servlet. Name() Servlet. Context get. Servlet. Context() Enumeration get. Init. Parameter. Names() String get. Init. Parameter(String name) Our interest will be in getting initialization parameters 8

Servlet init parameters n Where does a servlet get its initialization information? n n

Servlet init parameters n Where does a servlet get its initialization information? n n Inside <servlet>: n n From the web. xml file, of course! <init-param> <param-name>my. Name</param-name> <param-value>my. Value</param-value> </init-param> In the servlet code: n String my. Value = get. Servlet. Config(). get. Init. Parameter("my. Name"); 9

web. xml entire web application

web. xml entire web application

Multiple servlets n n A web application can consist of multiple servlets We just

Multiple servlets n n 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: n n <context-param> <param-name>my. Name</param-name> <param-value>my. Value</param-value> </context-param> In any servlet: n String my. Value = get. Servlet. Context(). get. Init. Parameter("my. Name"); 11

Servlet vs. context init parameters n Servlet init parameters are: n n Defined within

Servlet vs. context init parameters n Servlet init parameters are: n n Defined within a <servlet> tag Written within an <init-param> tag Retrieved from a Servlet. Config object, which you get by calling get. Servlet. Config() Read from the Servlet. Config object by calling get. Init. Parameter(name) n Context init parameters are: n n Defined outside all <servlet> tags Written within a <context-param> tag Retrieved from a Servlet. Context object, which you get by calling get. Servlet. Context() Read from the Servlet. Context object by calling get. Init. Parameter(name) 12

Public Servlet. Context methods n n n n String get. Init. Parameter(String name) Enumeration

Public Servlet. Context methods n n n n String get. Init. Parameter(String name) Enumeration get. Init. Parameter. Names() Object get. Attribute(String name) Enumeration get. Attribute. Names() void set. Attribute(String name, Object object) void remove. Attribute(String name) String get. Real. Path(String path) Request. Dispatcher get. Request. Dispatcher(String path) 13

servlet JSP

servlet JSP

The Servlet. Request object n You’ve seen these methods of the Servlet. Request object:

The Servlet. Request object n You’ve seen these methods of the Servlet. Request object: n n Servlet. Request also has these methods: n n public Enumeration get. Parameter. Names() public String get. Parameter(String name) public String[] get. Parameter. Values(String name) public Enumeration get. Attribute. Names() public Object get. Attribute(String name) public void set. Attribute(String name, Object object) You can use attributes to send information to the JSP 15

Dispatching to the JSP n request. set. Attribute(name, object) n n Notice that we

Dispatching to the JSP n request. set. Attribute(name, object) n n Notice that we put the information on the request Request. Dispatcher view = request. get. Request. Dispatcher("result. jsp"); n n We ask the request object for a dispatcher We supply, as a String, a path to the JSP file n n n 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); n n Having added the result information to the Http. Request object, we forward the whole thing to the JSP The JSP does the rest—it will send out the HTML page 16

Aside: redirect vs. forward n The previous slide showed how a servlet could forward

Aside: redirect vs. forward n The previous slide showed how a servlet could forward a request to JSP (or to another servlet) n n This is all done on the server side response. send. Redirect(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. ” n n 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 17

Attributes

Attributes

Parameters are not attributes n You can get parameters from the Deployment Descriptor: n

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

Attribute scopes n Servlets can access three scopes: n Application scope n n Session

Attribute scopes n Servlets can access three scopes: n Application scope n n Session scope n n All servlets in the web application have access Attributes are stored in the Servlet. Context object Available for the lifetime of the servlet Available to servlets that have access to this specific session Attributes are stored in the Http. Session object Available for the life of the session Request scope n n n Available to servlets that have access to this specific request Attributes are stored in the Servlet. Request object Available for the life of the request (until your do. Get or do. Post method completes) 20

Attribute methods n Servlet. Context objects, Servlet. Request objects, and Http. Session objects all

Attribute methods n Servlet. Context objects, Servlet. Request objects, and Http. Session objects all have the following methods: n Object get. Attribute(String name) n void set. Attribute(String name, Object object) n void remove. Attribute(String name) n Enumeration get. Attribute. Names() 21

Thread safety n Thread problems can occur when: n n n Thread problems cannot

Thread safety n Thread problems can occur when: n n n Thread problems cannot (in general) be detected by the Java runtime system n n 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 Instead, thread problems cause random, mysterious, non-replicable corruption of data There are simple steps that you can take to avoid many threading problems n However, threading is very error-prone and can be extremely difficult to ensure that you have it right 22

Thread safety in servlets n n Tomcat starts a new Thread for every new

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

Thread safety in class assignments n In reality, the servlets you write for this

Thread safety in class assignments n In reality, the servlets you write for this course are not going to service thousands of requests per second n n n 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. . . n n n 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 n n 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 24

Protecting context attributes n To protect context attributes, synchronize on the Servlet. Context object

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

Protecting session attributes n To protect session attributes, synchronize on the Http. Session object

Protecting session attributes n To protect session attributes, synchronize on the Http. Session object n Example (from Head First Servlets & JSP): Http. Session session = request. get. Session(); synchronized(session) { session. set. Attribute("foo", "22"); session. set. Attribute("bar", "42"); out. println(session. get. Attribute("foo")); out. println(session. get. Attribute("bar")); } n This will protect you from any other code that also synchronizes on the Http. Session 26

Getting init parameters in JSP n n You can get servlet and context init

Getting init parameters in JSP n n You can get servlet and context init parameters in your JSP Step 1: Specify in your DD that you want them: n n <servlet> <servlet-name>Some. Servlet. Name</servlet-name> <jsp-file>/Use. Servlet. Init. jsp</jsp-file> <init-param>. . . </init-param>. . . </servlet> Step 2: Override jsp. Init() (must be done in a JSP declaration): n <%! public void jsp. Init() { // use get. Servlet. Config() and get. Servlet. Context() as usual } %> 27

Page. Context n n In JSP, page. Context is an implicit object (like request

Page. Context n n In JSP, page. Context is an implicit object (like request and response) of type Page. Context has these methods (among others): n n Object get. Attribute(String name) // uses page scope Object get. Attribute(String name, int scope) Enumeration get. Attribute. Names. In. Scope(int scope) Object find. Attribute(String name) n n Searches in the order: page context, request scope, session scope, application scope void set. Attribute(String name, Object value) void set. Attribute(String name, Object value, int scope) Where scope can be one of Page. Context. APPLICATION_SCOPE, Page. Context. PAGE_SCOPE, Page. Context. REQUEST_SCOPE, or Page. Context. SESSION_SCOPE n So you can access a lot of information from a Page. Context object! 28

The End 29

The End 29