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 

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
Lecture 10 Sharing Resources. Basics of File Sharing The core component of any server is its ability to share files. In fact, the Server service in all.
COMP 321 Week 8. Overview MVC Example Servlet Lifecycle Servlet Mechanics MVC Lab 5-2 Solution Lab 8-1 Introduction.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Servlets and a little bit of Web Services Russell Beale.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
18-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
28-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Q: According to Intel, the Pentium conforms to the IEEE standards 754 and 854 for floating point arithmetic. If you fly in aircraft designed using a Pentium,
Servlet details Russell Beale. Servlet lifecycle The servlet container creates only one instance of each servlet Each use request handled with a separate.
Session-02.
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.
Struts 2.0 an Overview ( )
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Web server and web browser It’s a take and give policy in between client and server through HTTP(Hyper Text Transport Protocol) Server takes a request.
Lecture 18 Page 1 CS 111 Online Design Principles for Secure Systems Economy Complete mediation Open design Separation of privileges Least privilege Least.
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES LECTURE 5_1 George Koutsogiannakis/ Summer
Bill's Amazing Content Rotator jQuery Content Rotator.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
CGS – 4854 Summer 2012 Web Site Construction and Management Instructor: Francisco R. Ortega Chapter 2.
CSE 425: Concurrency III Monitors A monitor is a higher level construct for synchronizing multiple threads’ access to a common code segment –Can implement.
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.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
® IBM Software Group © 2007 IBM Corporation Servlet Listeners
Java Servlets & Java Server Pages Lecture July 2013.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
MVC Model 2 Architecture & AddressBook case study
Chapter 7 Being a JSP. JSP introduction JSP is a solution for two issues  Servlet is difficult for HTML designers since they may not know Java  Formatting.
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.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Java Server Pages (JSP)
11/18/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
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.
SE-2840 Dr. Mark L. Hornick1 Servlet Threads and Sessions.
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.
Java Enterprise Edition Programming Page 1 of 9Configuring Servlets Web Application Context Name  In multiple web applications, a “context name” is used.
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.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
MVC for Servlets 26-Apr-17.
A PC Wakes Up A STORY BY VICTOR NORMAN. Once upon a time…  a PC (we’ll call him “H”) is connected to a network and turned on. Aside: The network looks.
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.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
COOKIES AND SESSIONS.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5 Page 1 CS 111 Summer 2013 Bounded Buffers A higher level abstraction than shared domains or simple messages But not quite as high level as RPC.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Enterprise Java Beans. Contents  Understanding EJBs  Practice Section.
CS-4220 Dr. Mark L. Hornick1 Single class doing too many things =Bad Code Smell.
Servlet Sessions and Cookies
Java Servlets By: Tejashri Udavant..
Java Servlets.
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Pre-assessment Questions
Servlet API and Lifecycle
MVC for Servlets 23-Feb-19.
MVC for Servlets 29-Apr-19.
MVC for Servlets 5-Jul-19.
Presentation transcript:

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  For example, you entered your name and credit card info in one page and this info is displayed (shared) in another page, e.g., order confirmation page Your application may also want to hide information Your application also needs to be thread- safe

Make your servlet configurable Think about an example web application where you want to put your address in a servlet  Instead of hard code your in the servlet, it is better to make it configurable

Init parameters to the rescue

You cannot use servlet init parameters until the servlet is initialized Your servlet inherits getServletConfig() automajtically, so you can call that from any method in your servlet to get a reference to a ServletConfig  Once you have a ServletConfig reference, you can call getInitParameter() Remember you cannot call it from your constructor

You cannot use servlet init parameters until the servlet is initialized When the container initializes a servlet, it makes a unique ServletConfig for the servlet The container “reads” the servlet init parameters from the DD and gives them to the ServletConfig, the passes the ServletConfig to the servlet’s init() method

The servlet init parameters are read only ONCE When the Container makes a servlet, it reads the DD and creates the name/value pairs for the ServletConfig Once the parameters are in the ServletConfig, they won’t be read again until/unless you redeploy the servlet

How can a JSP get servlet init parameters A ServletConfig is for servlet configuration (it doesn’t say JSPConfig) How to pass the init parameters for a servlet to a JSP?  The request object lets you set attributes (think of them as a name/value pair where the value can be any object) that any other servlet or JSP that gets the request can use That means any servlet or JSP to which the request is forwarded using a RequestDispatcher

Setting a request attribute works… but only for the JSP to which you forward the request

How about I want some configurable info to be shared by all servlets and JSPs in my web application? You can use context init parameters  It work just like servlet init parameters, except context parameters are available to the entire webapp, not just a single servlet

Context init parameters

ServletConfig & ServletContext ServletConfig is one per servlet ServletContext is one per web app The container makes a ServletContext when a web app is deployed, and makes the context available to each Servlet and JSP (which becomes a servlet) in the web app

ServletConfig & ServletContext

Question Why would I ever use anyway? Wouldn’t I always want to use so that other parts of my application could reuse the values and I won’t have to duplicate XML code for every servlet declaration? Answer: It all depends on which part of your app is supposed to see the value

What else can you do with your ServletContext?

Listener What if you want an app init parameter that is a database DataSource?  You can certainly put the DataSource lookup name in a context init parameter, and that is probably the most common use of context parameter today  But then who does the work of turning the String parameter into an actual DataSource reference that all parts of the web app can share?

Listener (Cont.) You cannot really put that code in a servlet, because you cannot guarantee one servlet in particular will always run first You need to listen for a context initialization event, so that you can get the context init parameters and run some code before the rest of the app can service a client ServletContextListener can help  It is not servlet or JSP

What can listener do?

Example listener

Deploy the listener You need to create the listener class and put the class in WEB-INF/classes You also need to put a element in the web.xml Deployment Descriptor

An listener example public void contextInitialized (ServletContextEvent event){ try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { System.out.println("*****Error loading the driver*******"); } try { conn = DriverManager.getConnection("jdbc:mysql://localhost/j2ee?user=root&password="); ServletContext sc = event.getServletContext(); sc.setAttribute("dbconnection1", conn); System.out.println("*******set dbconnection attribute *******"); } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }

An listener example public void contextDestroyed (ServletContextEvent event){ try{ conn.close(); conn = null; }catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }

web.xml for the listener edu.nku.j2ee.MysqlContextListener

What is an attribute? You can think of it as simply a name/value pair (where the name is a String and the value is an Object) in a map instance variable In reality, we really care about the scope in which the attribute exists.  In other words, who can see it and how long does it live.

Attributes Three scopes:  Context  Request  Session

Attributes are not parameters

Context attributes

Session attributes

Request attributes

Attribute API The three attribute scopes – context, request, and session – are handled by the ServletContext, ServletRequest, HttpSession interfaces The API methods for attributes are exactly the same in every interface

The dark side of attributes... Kim decides to test out attributes. He sets attribute and then immediately gets the value of the attribute

Here is what he sees the first time he runs it

But then something goes horribly wrong Kim put this code in a test servlet that is part of a larger test web app. In other words, the servlet that holds this doGet() method was deployed as part of a larger app. Can you figure out what happened? How to fix it?

Context scope is not thread-safe Remember everyone in the app has access to context attributes  Since requests are concurrently handled in separate threads, You may have multiple servlets (mean you might have multiple threads) accessing the context attributes concurrently You may have multiple threads from one servlet accessing the context attributes concurrently Either of the above two cases can cause problems

context attributes’ thread-safe issue Can we synchronize doGet() method to make it thread safe?

context attributes’ thread-safe issue No.  Synchronize doGet() will not only kiss your concurrency goodbye, but also does not protect context attributes at all Synchronizing the service method would stop other threads from the same servlet from accessing the context attributes, but it won’t do anything to stop a completely different servlet

context attributes’ thread-safe issue By the way, the figure in Page 192 and 196 of our book has a little bit of problem…  It draws two instance of servlet A, it is a little confusing By default, one instances of a servlet is responsible for taking care of multiple requests coming in to the same servlet If you look at figure at P101 of the book, you will be very clear

context attributes’ thread-safe issue You don’t need a lock on the servlet… you need the lock on the context If everyone accessing the context has to first get the lock on the context object, then you’re guaranteed that only one thread at a time can be getting or setting the context attribute  It only works if all of the other code that manipulates the same context attributes ALSO synchronize on the ServletContext  If code doesn’t ask for the lock, then that code is still free to hit the context attribute

The right way to synchronize context attribute’s multiple concurrent access

Are session attributes thread-safe? We have not talked about HTTP sessions in detail yet, but you already know that a session is an object used to maintain conversational state with a client The session persists across multiple requests from the same client And if it’s one client, and a single client can be in only one request at a time, doesn’t that automatically mean that session are thread- safe?

Are session attributes thread-safe? No.  The client could open a new browser window (from the same browser)  The container can see the request from the second window (of the same browser) as coming from the same session

Correct way to synchronize accessing to session attributes You can protect session attributes by synchronizing on the HttpSession object

Question Isn’t it a bad idea to synchronize code, because it causes a lot of overhead and hurts concurrency? Answer: You should always think carefully before synchronizing any code, because you’re right-it does add some expense in checking, acquiring, and releasing locks. If you need protection, then use synchronization but remember the standard rule of all forms of locking-keep the lock for the shortest amount of time to accomplish your goal!

Request attributes and local variables Only request attributes and local variables are thread-safe Everything else is subject to manipulation by multiple threads, unless you do something to stop it

Request attributes and request dispatching Request attributes make sense when you want some other component of the app to take over all or part of the request  The component that take over the request will be able to access the request attributes Our typical simple example is an MVC app that starts with a servlet controller, but ends with a JSP view We can make another part of the component take over the request with a RequstDispatcher

Request attributes and request dispatching