Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

WEB PROGRAMMING WITH JSP & SERVLET

WEB APPLICATION

CONTENTS
Applications HTTP protocols Evolution of Servlets Web Application Web Application Development Process Servlet API Workshops Exercises

A collection of programs is designed to perform a particular task (different purposes) Classification (based on running and accessibility)
Local machine Single user

APPLICATIONS

LAN, WAN, or MAN


Muli-users in particular network only

Web Server Multi-users having administrator or equivalent privileges Browsing with Web Browser

APPLICATIONS (cont)

Advantages of Web Application


Easier access to information (HTTP, Web Browser) Lower maintenance (modified at the server end) and deployment costs (not installation) Platform independency Wider visibility (access all around the world)

Limitation of Web Servers


Not feasible to maintain static content from the customers end (Static Web is built by Web designer) Can not be managed the dynamic Web contain from client Overloading errors (Web servers) Unavailability due to maintenance Heavy traffic High maintenance costs Virus or worms attacks

HTTP PROTOCOLS
1. Convert http://microsoft.com/ to 192.168.54.3:80 Connect

2. Send a request to Web Server (index.html)


4. The result is responsed to Browser

http://microsoft.com/index.html
5. Web Browser views the result which contains a markup language 192.168.54.3:80 3. Web Server processes a request (connecting DB, calculating, call service )

Request Response pairs Stateless Port 80 is default

REQUEST MESSAGE
A Stream of text
Return method Resource information (type&name, HTTP version) Ex: GET image/bar01.jsp HTTP/1.1

Return the User-Agent (the browser) along with the Accept header Blank line (provides information on what media types the client can accept)
Ex: User-Agent: Mozilla/4.0 (compatible: MSIE 4.0 : Windows 95) Accept : image/gif, image/jpeg, text/*, */*

REQUEST OBJECTS
1. Forms information is sent to Web Server using request parameter.
4. The result of processing is responsed

GET:
Is the method commonly used to request a resource/ get information (access static resource such as HTML doc and images or retrieve dynamic information such as query parameters) from server The length of query string is restricted 240 to 255
2. Server process requested client (server script Server Side), connect DB ...
3. Connect

POST:
Is the method commonly used for passing user input/ sending information to the server (access dynamic resources and enable secure data in HTTP request because the request parameters are passed in the body of request) No limit and Cannot be booked mark or emailed
Database

RESPONSE MESSAGE
Indicates status of request process (HTTP version, response code, status) Ex: HTTP/1.1 200 OK

Server. Ex: Server: JavaWebServer Last modified date. Ex: Last-modified: Tuesday, 24-Mar-09 8:30:34 GMT Content length. Ex: Content-length: 100 Content type. Ex: Content-type: text/plain

A small program (*.exe) is written in languages such as C/C++, Perl, ... for the gateway programs. Used in complex applications, such as Web pages A set of standards followed to interface applications form client side to a Web Server Enables the Web server to send information to other files and Web browsers Helps to process the inputs to the form on the Web page Helps to process the inputs to the form on the Web page Enables to obtain information and use it on the server machine (server side) When the Browser sends request to server, CGI instantaties to receive and process.

CGI

CGI
Disadvantages
Reducing efficiency Reloading Perl interpreter Interactive: not suitable for graphical or highly interactive programs Time consuming and more memory consumed Debugging: error detection is difficult Not support Session

SERVLETs
Is a Java code to generate the HTML and support the dynamic web pages A server side scripting is not requirement of reloading the Servlet compiler each time a request is received from client Using multi threading (Overcome CGIs consumed more memory) Gets auto refreshed on receiving a request each time A Servlets initializing code is used only for initializing in the 1st time Merits
Enhanced efficiency (initializing only once, auto refresh) Ease to use (using Java combining HTML) Powerful (using Java) Portable Safe and cheap

Demerits
Low-level HTML documentation (Static well-formed-ness is not maintained) Unclear-session management (flow of control within the codes is very unclear)

WEB APPLICATION Registered into WWW Accessible from a public server Comprises servlets, JSPs, images, HTML, JavaBeans, applets, and Java classes Portability (easy copy/move or alternative) Store in single WAR file to deploy on the Web server Web Container
Is a program that manages execution of servlets and JSP pages Take requests from a Web Server and passes it to a servlet for processing Maintains the servlet life cycle

WEB APPLICATION DIRECTORY STRUCTURE

Above structure is packaged into *.war file to deploy on Web Server

WEB DEPLOYMENT DESCRIPTOR web.xml


<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>servlet name</servlet-name> <servlet-class>[package.]classname</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet name</servlet-name> <url-pattern>/context Path/root</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>default page to show</welcome-file> </welcome-file-list> </web-app>

EXAMPLE
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.sample.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>HelloServlet</welcome-file> </welcome-file-list> </web-app>

WEB APPLICATION DEVELOPMENT PROCESS Requirement tools: NetBeans 5.5.1 Step 1: Creating a new project Step 2: Creating the new Web files. Step 3: Specifying Name and Location for the Project Step 4: Specifying the Name of the Servlets Step 5: Writing the code for Servlet & Compile Step 6: Package Servlet into WAR file Step 7: Deploying in a Web Container Step 8: Executing the Servlet

Step 1: Creating a new project

Click menu File Click the New Project Items

Step 2: Creating the new Web files.

Click Web categories Click the Web Application Projects Click Next button

Step 3: Specifying Name and Location for the Project

Fill your project name Browser your location where store the project

Choose deployed server (Tomcat is default) Choose J2EE 1.4 Modify the context path (if necessary). Defaults, it is named same as Project Name

Click Finish button

WEB APPLICATION DIRECTORY STRUCTURE in NETBEANS


Project name
Interactive Web Directory

Web Deployment descriptor

Configuration directory related define for Web App

Source java class required for Web App

Lib directory required for Web App

Step 4: Specifying the Name of the Servlets

Click Web categories Click the Servlet File Types Click Next button

Step 4: Specifying the Name of the Servlets (cont)


Fill your servlet name

Fill or choose package name

Click Next button

Step 4: Specifying the Name of the Servlets (cont)

Modify the Servlet Name or URL Pattern if necessary) to configure the servlet information to web.xml

Click Finish button The servlet class (ex: HelloServlet.java) is added to source packages (with package name if its exist) and its information is added to xml

Step 5: Writing the code for Servlet & Compile


Modify the processRequest method in servlet class. Ex:
protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType ("text/html;charset=UTF-8"); PrintWriter out = response.getWriter (); out.println("<html>"); out.println("<head>"); out.println("<title>Hello Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Welcome to Servlet course</h1>"); out.println("</body>"); out.println("</html>");
out.close ();

Step 5: Writing the code for Servlet & Compile (cont)

Step 6: Package Servlet into WAR file

Package War file with command prompt


jar cvf fileName.war directoryOrFile (using blank to separate) Ex: jar cvf HelloServlet.war *.jsp WEB-INF/*

Step 7: Deploying in a Web Container

Step 8: Executing the Servlet

CAREFULNESS
Notes:
Web Server should be started before the Web application is deployed or run

Should stop the web server when modifying Should execute undeploy action when the same errors occur (the error was corrected anyway)

ADDITIONAL using wizard to web.xml


Modify servlet name

Modify URL Pattern Add existing servlet to Web App


Remove selected servlet from Web App

Change servlet class

Process with init parameter of Servlet

ADDITIONAL (cont) testing any selecting servlet in project

Click Ok button to test selected servlet

ADDITIONAL (cont) hint

Caches of server
C:\Documents and Settings\Trong Khanh\.netbeans\5.5.1\apachetomcat-5.5.17_base\work\Catalina\localhost\ C:\Users\usernames\.netbeans\5.5.1\apache-tomcat5.5.17_base\work\Catalina\localhost\ Above location should be gone and cleared when the application cannot undeploy or the web servers occur the errors

Defines a servlet that is not protocol dependent Implements the Servlet and the ServletConfig interfaces Retrieves the configuration information by implementing the ServletObject Some methods
Methods Descriptions - public void init() throws ServletException - Initialises the servlet public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException - Called by the container to respond to a servlet request

GenericServlet Class

init

service

getInitParameter

- public String getInitParameter(String name) - Return a String containing the value of name initialisation
- public ServletContext getServletContext() - Returns the ServletContext in which this servlet instance is running - public ServletConfig getServletConfig() - returns the servlet configuration objects of this servlet instance - public String getServletInfo() - returns the useful servlet information on the name of the creator of the servlet, version information and copyright information

getServletContext getServletConfig

getServletInfo

HttpServlet Class
Provides an abstract class to create an HTTP Servlet Extends the GenericServlet class A subclass of HttpServlet class must override at least one of the following methods: doGet(), doPost, doPut(), doDelete(), init(), destroy(), and getServletInfo Some methods to process the request
Methods Descriptions

doGet

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - called by container to handle the GET request. - This method is called through service() method - protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - called by container to handle the POST request. - This method is called through service() method

doPost

WORKSHOP ACTIVITIES

Building the first Servlet named HelloServlets to greet the user Hello Servlets in the Web browser. Notes: The NetBean runs the Servlet with the Tomcat Server version 5.5.9

EXERCISES
Do it again all of demos Using servlet to write the programs that can do
Present the Login form (naming LoginServlet) with title Login, header h1 Login, 02 textbox with naming txtUser and txtPass, and the Login button Writing the ColorServlet that presents Welcome to Servlet course with yellow in background and red in foreground Writing the ProductServlet includes a form with a combo box containing Servlet & JSP, Struts & JSF, EJB, XMJ, Java Web Services, and the button with value Add to Cart

You might also like