Download Java Servelets - Information Services and Technology

Document related concepts
no text concepts found
Transcript
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. The Web site
says that it is restarted every hour, and takes about 3
minutes to restart. See the last slide in this lecture for
more information on using Tomcat on AFS.
AFS Resources
• See the left hand menu at http://ist.njit.edu/ especially
http://ist.njit.edu/support/tomcat.php
• 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!
Servlet Definition
• Servlets are protocol- and platformindependent server side components, written
in Java, which dynamically extend Javaenabled 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.
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.
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.
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.
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 :-).
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.
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.
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.
Servlet Advantages
RamaKrishna Dantuluri
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.
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.
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.
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.
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.
How to Implement Servlets
Kalpesh Patel
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.
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.
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.
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)
Init Example
• private String databaseURL;
public void init(ServletConfig config)
throws ServletException {
super.init(config);
databaseURL =
config.getInitParameter("database");
}
How to Implement Servlets on personal
computers and on AFS
Chandra Mouli Guda
Note: I would welcome having this
lecture updated for Eclipse
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.
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”
Create a new web application
Understanding the Project Folder
• It is very important to understand the
structure of Project folder created for a web
application after building a project.
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
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.
Hello.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
}
}
Hello.java description
Lines 1 through 4 - import statements
These are the minimum number of Java packages that need to be imported that are required for
a web servlet
Line 5 - servlet class declaration
Class definition for a servlet which extends HttpServlet
Lines 6 and 7 - doGet() Override
Overriding the doGet() method
Notice that both a ServletException and IOException must be thrown
Line 8 - Setting the content type
sets 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 object
PrintWriter 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 PrintWriter
Closing a PrintWriter at the end of a method is a standard practice of Java Servlet developers
Web Description
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.
• Drive:\ProjectServlet\build\web\WEB-INF\web.xml
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
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.
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.
http://localhost:8084/MyFirstServletProject/MyFirst
Servlet/
• 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.
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.
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>
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
Connection to Prophet Database
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.
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.
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”
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
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.
Connection to Prophet Database
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.
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.
Code to connect JDBC to AFS
try {
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
// establish connection to the database
String con = "jdbc:oracle:thin:@prophet.njit.edu:1521:course";
//Create a connection to talk to database
Connection con = DriverManager.getConnection(con,user,password);
…….
……..
Sql commands here and store in the Resultset
……
} catch (SQLException e) {}
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
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);
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.
Servlet Security
Ranjini Nair
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".
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.
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.
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
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.
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.
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)
Unsafe Servlet example (1)
• private String someParam;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
someParam = request.getParameter("someParam");
processParam();
}
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.
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);
}
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.
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.
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, each day before you can test your servlet.
(Don’t wait until the last day!)