700 likes | 1.41k Views
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.
E N D
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.
AFS Resources • See the left hand menu athttp://web.njit.edu/especiallyhttp://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!
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.
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”
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 • 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.
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/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.
Congratulations!!! • Now while your project is running, type the path where your servlet is stored i.e.. localhost:8084/MyFirstServlet/servlet/Hellowhich 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 • 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) {}