java servlets ramakrishna dantuluri, ranjini nair, kalpesh patel, chandra mouli guda

67
Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Post on 19-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Java Servlets

RamaKrishna Dantuluri,Ranjini Nair, Kalpesh Patel,

Chandra Mouli Guda

Page 2: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Warning• If you are implementing servlets using Tomcat on

AFS you will have to wait until the server is restarted before your code can be tested.

• It will not work until the server is restarted at 6 a.m., 2 p.m., and 8 p.m. daily. It takes about half an hour to restart each time as Tomcat has to check about 5,000 home directories for JSP and servlets. See the last slide in this lecture for more information on using Tomcat on AFS.

Page 3: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

AFS Resources• See the left hand menu at http://web.njit.edu/ especially

http://web.njit.edu/all_topics/Servers/Tomcat/ • To use Tomcat on AFS, go to your public_html

directory and run the script tomcat.setup. This will install Tomcat and also give you working demos of both JSP and servlets. The demos are running on the professor’s Web site at the bottom of this page:

• http://web.njit.edu/~gblank/cis602/StealThis.html • The demos listed above can also be used to test

Tomcat on AFS. If they work, the problem is in your code, not AFS!

Page 4: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Definition

• Servlets are protocol- and platform-independent server side components, written in Java, which dynamically extend Java-enabled servers.

• They have become more and more popular as they benefit from all the advantages of the Java programming language in particular Architecture and Platform Independence and the ability to build robust and secure applications.

Page 5: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

The Servlet Interface

• A Servlet, in its most general form, is an instance of a class, which implements the javax.servlet.Servlet interface.

• Most Servlets, extend one of the standard implementations of that interface, usually javax.servlet.http.HttpServlet.

• HTTP Servlets extend the javax.servlet.http.HttpServlet class.

Page 6: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Definition

• Servlets are to a server what applets are to client browsers. Because Servlets run within the server there is no graphical user interface. Communication with a Servlet occurs through the Server API, which although not part of the core Java framework is supported my many manufacturers as an add-on.

Page 7: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Definition

• A Servlet, in simple terms, is a Java program running under a web server taking a 'request' object as an input and responding back by a 'response' object. Typically a web browser will send the request in HTTP format. The Servlet container will convert that into a request object. Similarly the response object - populated by the Servlet is converted into an HTTP response by the Servlet container.

Page 8: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Definition

• This mechanism makes the browser - web server interaction very easy. Java Servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and many alternative CGI-like technologies.

• (More importantly, Servlet developers tend to get paid more than Perl programmers :-).

Page 9: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Definition

• Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations.

• But most CGI variations, including Servlets, make you generate the entire page via your program, even though most of it is always the same.

Page 10: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Mechanics

• A servlet is a Java class and thus needs to be executed in a Java Virtual Machine by a service called a servlet engine. The servlet engine loads the servlet before it can be used. The servlet then stays loaded until it is unloaded or the servlet engine is shut down.

Page 11: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Engines• Some web servers, including Sun Java Web

Server, W3C Jigsaw, and Gefion LiteWebServer are implemented in Java and have a built in servlet engine. High end commercial servers like Websphere and Web Logic tend to include a servlet engine. Other web servers such as Microsoft IIS and Apache require a servlet add-on module which must be loaded separately.

Page 12: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Advantages

RamaKrishna Dantuluri

Page 13: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Advantages

• Possibly the biggest advantage of Java Servlets is that they run within the context of the server. This along with the multithreading characteristic of Java means that the server doesn’t have to begin a new process for every request made. Instead, the server creates a single instance of the Servlet, which handles all client requests, thus allowing Servlets to out perform both the CGI approach and the Fast-CGI approach.

Page 14: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Comparing Servlets to CGI

• Servlets are more efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time.

• With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process.

Page 15: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Comparing Servlets to CGI• Servlets also have more alternatives than do

regular CGI programs for optimizations, such as caching previous computations and keeping database connections open.

• Servlets are more convenient. Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such tasks.

Page 16: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Comparing Servlets to CGI• Java Servlets can do things that are difficult or

impossible with regular CGI: – Talk directly to the Web server. This simplifies

operations that need to look up images and other data stored in standard places.

– Share data with other Servlets, making useful things like database connection pools easy to implement.

– Maintain information from request to request, simplifying things like session tracking and caching of previous computations.

Page 17: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Java Web Server

• In order to run Java Servlets you will need the JavaWebServer. If you do use the JavaWebServer you will need Third-party Servlet containers. Java can be difficult for some programmers to learn.

Page 18: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

How to Implement Servlets

Kalpesh Patel

Page 19: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Init Method

• A Servlet is a Java class that implements the Servlet interface. This interface has three methods that define the Servlet's life cycle:

• public void init(ServletConfig config) throws ServletException

• This method is called once when the Servlet is loaded into the Servlet engine, before the Servlet is asked to process its first request.

Page 20: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Service Method

• public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

• This method is called to process a request. It can be called zero, one or many times until the servlet is unloaded. Multiple threads (one per request) can execute this method in parallel so it must be thread safe.

Page 21: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Destroy Method

• public void destroy() • This method is called once just before the

Servlet is unloaded and taken out of service.• The init method has a ServletConfig attribute.

The Servlet can read its initialization arguments through the ServletConfig object. How the initialization arguments are set is Servlet engine dependent but they are usually defined in a configuration file.

Page 22: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Initialization Arguments

• A typical example of an initialization argument is a database identifier. A servlet can read this argument from the ServletConfig at initialization and then use it later to open a connection to the database during processing of a request: (next slide)

Page 23: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Init Example

• private String databaseURL;

public void init(ServletConfig config) throws ServletException {super.init(config);databaseURL = config.getInitParameter("database");}

Page 24: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

How to Implement Servlets on personal computers and on AFS

Chandra Mouli GudaNote: I would welcome having this

lecture updated for Eclipse

Page 25: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Setup• Till now we discussed Servlets and its methods. Now,

let us try to configure personal machines to run servlets.

• Configuring servlets to run on some servers is sometimes difficult and time consuming, because each application server is different.

• This example uses Netbeans. The class is now using Eclipse. There are good tutorials on Servlets with Eclipse available on the Web. Review this presentation to understand the concept, then use an Eclipse tutorial to implement your own Servlets.

Page 26: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Setup

• We would go step by step to setup a web application using Netbeans 5.5.

• Select File-> “New Project” select Categories-> “web” Project -> “ Web Application”• Enter Details of Project Name and

Location and click “Finish”

Page 27: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Create a new web application

Page 28: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Understanding the Project Folder

• It is very important to understand the structure of Project folder created for a web application after building a project.

Page 29: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Create a New servlet File

• Notice when the project is created a jsp page called “index.jsp” is displayed which is made to run every time we run the tomcat server.

• We can edit this page to create links to ones html pages and other servlets.

• Now, go to “Source Packages” and right click to create a java servlet

Page 30: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

New Servlet Class

• The Servlet class extends HttpServlet and many functions are displayed that can be overridden.

• Now you are ready to write your first servlet class.

• Type the following code to display “Hello” on a servlet webpage.

Page 31: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Hello.java

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException { res.setContentType("text/html");

PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1><font color='green'>Hello

World!</font></h1>"); out.println("</body>"); out.println("</html>"); out.close();

} }

12345678910111213141516

Page 32: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Hello.java description

Lines 1 through 4 - import statementsThese are the minimum number of Java packages that need to be imported that are

required for a web servlet Line 5 - servlet class declarationClass definition for a servlet which extends HttpServletLines 6 and 7 - doGet() OverrideOverriding the doGet() method Notice that both a ServletException and IOException must be thrown Line 8 - Setting the content typesets the content type for the servlet to send back as a HttpServletResponse the content type must be set before a ServletOutputStream or PrintWriter are

declared Line 9 - declaring a PrintWriter objectPrintWriter out will be used to write text to a response Lines 10 through 13 - "out.println"Writing out the html code as determined by "text/html" Line 14 - Closing the PrintWriterClosing a PrintWriter at the end of a method is a standard practice of Java Servlet

developers

Page 33: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Web Description

• Drive:\ProjectServlet\build\web\WEB-INF\web.xml is the source of the web descriptor which needs to be modified to enable Hello Servlet to function. Build your project first.

• This xml file contains a log file for every session to http.

• Warning! Do not change the xml files in any other Tomcat directory as this would require you to rebuild or recreate your project.

Page 34: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Web Description

• Double click the xml file and you see a display window click on servlets menu and “browse” for servlet class Hello.java

• Select the url pattern you want for servlet & save

Page 35: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Web Description

• These set of instructions enable the tomcat server to recognize Hello servlet.

• <servlet-mapping> the path which follows here should be the place where the servlet class is stored please be careful when you compile servlet into a package use the path as

<servlet-mapping>package.”servlet_name”</servlet-mapping>

• If you compile a project frequently, It is best to store a copy of the xml file. That will replace the 7kb default xml.

Page 36: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Running of Hello Servlet

• Now compile your project folder and run it.

• Once successfully built this project would start the tomcat server and open a web browser with a message called JSP Page.

• Notice the JSP page which has a path as local host.

Page 37: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

http://localhost:8084/MyFirstServletProject/MyFirstServlet/

• This path specifies that Tomcat is running on your personal computer acts a local host server listening through port 8084.

• Now your PC is a server as well as a client where client is the servlet page and server is the Tomcat running in Netbeans.

• Port 8084 redirects IP addresses to the host where it opens the webpage on your own computer.

Page 38: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Congratulations!!!

• Now while your project is running, type the path where your servlet is stored i.e.. localhost:8084/MyFirstServlet/servlet/Hello which is your url-pattern for the servlet.

Page 39: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

How do you upload this servlet onto AFS?

• Copy your .class files into the classes folder in WEB-INF folder on afs and place the web.xml outside the classes folder within WEB-INF folder.

• Notice if you have any other JSP and HTML files keep them in your public_html folder or package folder. Be sure you give correct path.

• There is no folder called “servlet” created, It is the default used by Tomcat Web container in AFS to specify the path for servlets.

• The path for your servlet would be http://web.njit.edu/~ucid/servlet/<servlet-name>

Page 40: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Summary

• Create a web application• Add a new java servlet class• Edit the xml file to have servlet and its url-

pattern established • Write a jsp or a html front-end to the servlet

and run the project.• In the browser specify the url-pattern to the

localhost.• For further details on servlets check the link

http://users.dickinson.edu/~sentzm/st/sec1.html

Page 41: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

Chandra Mouli Guda

Page 42: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• Things get complicated when we try to establish a connection with our prophet database as there are lot of security restrictions.

• Every student who enrolls for this course get a user space in prophet database and the user-id and password are sent to them by mail in the beginning of semester.

Page 43: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• In order to establish the connection from your personal computer you need the oracle-10g thin driver(ojdbc14.jar) which can be obtained from the oracle website

• http://www.oracle.com/technology/software/products/database/oracle10g/index.html

• Download the jar file and place it under the java directory C:\Program Files\Java\jdk1.5.0_09\lib\

• Set the path to lib by setting the environment variables of your system.

Page 44: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• Notice the Runtime tab in Netbeans 5.5 which shows details of servers, processes, databases, Http servers etc.

• We need to create a database connection here to connect to prophet database.

• Click on “Databases” and Right click on subdirectory “Driver” to “new driver”

Page 45: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• Click on “Add” and add the jar file it automatically detects OracleDriver class and then give a name in the name field

Page 46: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• A new driver is created now go and right click the driver and click on “connect using”

• A window pops up called New JDBC connection• Add details: • name: choose the drive you created• Database url:

jdbc:oracle:thin:@prophet.njit.edu:1521:course• Give the user id and password for the prophet database

that was given to you by email when you registered for this course.

• Click ok and notice a new link created on databases.

Page 47: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

Page 48: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Connection to Prophet Database

• Now you are ready to connect to the database but make sure you are connected to VPN before you try to connect to database if outside college network.

• Connect to VPN, right click on New Connection, and give user id and password

• The Connection is established and you can create tables right within Netbeans without logging into the Prophet account and type SQL commands. It is faster and simpler.

Page 49: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Basic rules to connect to JDBC

• If you are implementing the project on your personal computer make sure you extract the folder “oracle” under ojdbc14.jar and place it in classes folder of your project.

• However, while uploading to AFS it isn’t required since AFS already has the Oracle drivers installed.

Page 50: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Code to connect JDBC to AFS

try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); // establish connection to the databaseString con = "jdbc:oracle:thin:@prophet.njit.edu:1521:course";//Create a connection to talk to databaseConnection con =

DriverManager.getConnection(con,user,password);…….……..Sql commands here and store in the Resultset……} catch (SQLException e) {}

Page 51: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

General tips to connect to JDBC

• Always surround database calls in try catch with SQLException.

• Once the communication is done make sure you close your Resultset and connection. This is crucial or you will not be able to get back into Oracle.

• You can go on to the link and try implementing the Test.java code from http://web.njit.edu/~gblank/cis633/Lectures/Prophet.doc

Page 52: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Tips for effective results

• When you create tables do not frequently modify the structure of tables. This may conflict with the new tables created.

• Use the prepared statement command to modify, add, or delelete records in database with the format

• "INSERT INTO Table_Name (names of columns in table) VALUES (?,?)");

• And pass the parameters now specifying the column number and variable containing the data such as

stmt.setString(column number, variable);

Page 53: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Example code to add record

Connection con = DriverManager.getConnection(url,user,password); // pull the data from the database and store in a ResultSet PreparedStatement stmt = null;

stmt = con.prepareStatement("INSERT INTO Table_name(NAME,AGE,COURSE) VALUES (?,?,?)");

stmt.setString(1,name); stmt.setString(2,age);

stmt.setString(3,course); ResultSet res1 = stmt.executeQuery(); // executes the query res1.close(); // closes the resultset con.close(); // very important

Here name, age , course in stmt.setString commands is the data which is already present as String variables.

Page 54: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Security

Ranjini Nair

Page 55: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Sand Box

• A Servlet can originate from several sources. A user may have written it or it may have been bought as part of a third-party package or downloaded from another web site.

• Based on the source of the Servlet, a certain level of trust should be associated with that Servlet. Some web servers provide a means to associate different levels of trust with different Servlets. This concept is similar to how web browsers control applets, and is known as "sandboxing".

Page 56: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Analogy: A child’s sandbox

• A children’s sandbox provides a safe place for them to play, and keeps the sand clean and prevents it from spilling out. The Java sandbox isolates what you are working on from the rest of the system.

Page 57: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet Sand Box (2)

• A servlet sandbox is an area where servlets are given restricted authority on the server. They may not have access to the file system or network, or they may have been granted a more trusted status. It is up to the web server administrator to decide which servlets are granted this status. Note that a fully trusted servlet has full access to the server's file system and networking capabilities. It could even perform a System.exit(), stopping the web server.

Page 58: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Access Control Lists (ACL)

• Access Control Lists (ACLs) Many web servers allow you to restrict access to certain web pages and servlets via access control lists (ACLs). An ACL is a list of users who are allowed to perform a specific function in the server. The list specifies: – What kind of access is allowed – What object the access applies to – Which users are granted access

Page 59: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

ACL Specification

• Each web server has its own way to specify an ACL. In general, a list of users is registered on the server, and those user names are used in an ACL. Some servers allow adding users to logical groups, so you can grant access to a group of users without specifying individuals explicitly.

• ACLs are important, as some Servlets might modify sensitive data and need tight control, while others only present public knowledge and do not need control.

Page 60: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Threading with Servlets

• A web server can call a servlet's service() method for several requests at once. This brings up the issue of thread safety in servlets.

• A servlet's init() method will only be called once for the duration of the time that a servlet is loaded. The web server calls init()when loading, and will not call it again unless the Servlet has been unloaded and reloaded. The service() method or destroy() method will not be called until the init()method has completed its processing.

Page 61: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Servlet methods

• The doGet(), doPost() and service() methods can be called by the web server for multiple clients at the same time. It's therefore important that these methods are thread safe.

• The easiest way to guarantee that the code is thread safe is to avoid instance variables altogether and instead pass all information needed by a method as arguments. For instance: (code on next slide)

Page 62: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Unsafe Servlet example (1)

• private String someParam;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

someParam = request.getParameter("someParam");processParam();}

Page 63: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Unsafe Servlet example (2)

• private void processParam() {// Do something with someParam}is not safe. If the doGet method is executed by two threads it's likely that the value of the someParam instance variable is replaced by the second thread while the first thread is still using it.

Page 64: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Safe Servlet example (1)

• A thread safe alternative is:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

someParam = request.getParameter("someParam");processParam(someParam);}

Page 65: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Safe Servlet example (2)

• private void processParam(String someParam) {// Do something with someParam}Here the processParam gets all data it needs as arguments instead of relying on instance variables. Access to class and instance variables must be protected by using Java’s synchronized keyword.

Page 66: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Conclusion

• Another reason to avoid instance variables is that in a multi-server system, there may be one instance of the Servlet for each server and requests for the same Servlet may be distributed between the servers. Keeping track of information in instance variables in this scenario doesn't work at all. In this type of system you can instead use the HttpSession object, the ServletContext attributes, or an external data store such as a database.

Page 67: Java Servlets RamaKrishna Dantuluri, Ranjini Nair, Kalpesh Patel, Chandra Mouli Guda

Hints for Servlets on AFS• Tomcat is already installed on AFS.• There is a very simple working example of

Servlets with JDBC in the Tomcat tutorials at http://web.njit.edu . Add functionality to that if you use it!

• You will have to wait for Tomcat to be restarted at 6 am, 2 pm, and 8 pm before you can test your servlet. (Don’t wait until the last day!)