0% found this document useful (0 votes)
29 views21 pages

Chapter4 Installation - and Servlets

The document provides a comprehensive guide on creating and deploying a Java web application using NetBeans IDE and Apache Tomcat. It covers the structure of a Java web application, including the root directory, WEB-INF directory, and web.xml configuration file, along with servlet lifecycle management and HTTP request/response handling. Additionally, it includes practical examples for creating servlets and handling client requests through forms.

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views21 pages

Chapter4 Installation - and Servlets

The document provides a comprehensive guide on creating and deploying a Java web application using NetBeans IDE and Apache Tomcat. It covers the structure of a Java web application, including the root directory, WEB-INF directory, and web.xml configuration file, along with servlet lifecycle management and HTTP request/response handling. Additionally, it includes practical examples for creating servlets and handling client requests through forms.

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

4.

1 Creating java web application project in netbeans IDE >>


Select Apache Tomcat Server >>

select install

directory of Tomcat and insert username and password >>


(Tomcat installation, setup and deployment will cover in 4.5)

This is
how we

create web application in netbeans IDE


4.2 Structure of java web application project >>

The Root Directory >>


The root directory of your web application can have any name. In the above example the root
directory name is mywebapp .
Under the root directory, you can put all files that should be accessible in your web application.
If your web application is mapped to the URL http://localhost:8080/mywebapp/ then the
index.html page will be accessible by the URL http://localhost:8080/mywebapp/index.html
If you create any subdirectories under the root directory, and place files in these subdirectories,
these will be available by the subdirectory/file path

The WEB-INF Directory >>


The WEB-INF directory is located just below the web app root directory. This directory is a meta
information directory. Files stored here are not supposed to be accessible from a browser (although
your web app can access them internally, in your code).
Inside the WEB-INF directory there are two important directories (classes and lib, and one
important file (web.xml). These are described below.

web.xml >>
The web.xml file contains information about the web application, which is used by the Java web
server / servlet container in order to properly deploy and execute the web application. For instance,
the web.xml contains information about which servlets a web application should deploy, and what
URL's they should be mapped to.
The classes directory >>
The classes directory contains all compiled Java classes that are part of your web application. The
classes should be located in a directory structure matching their package structure.

lib folder >>


The lib directory contains all JAR files used by your web application. This directory most often
contains any third party libraries that your application is using.
Instead of copying entire directory into server we can package them into war file and then do the
deployment.
4.4
4.4.1 Web.xml >>>
Web.xml defines mapping between URL paths and servlets that handle requests with those paths.
The web.xml file provides configuration and deployment deployment information for the Web
components that comprise a Web application. The web.xml descriptor files represents the core of the
java application. The web.xml file is located in WEB-INF directory of web application.
Example of web.xml File:
[code lang=”xml”]
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>servletexample.createHelloWorldExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloworldExample/*</url-pattern>
</servlet-mapping> </web-app> [/code]

Elements in Web.xml >>


Description of elements Used in web.xml file:
<web-app>: This element represents whole application of web.xml file

<servlet>: This is the sub element of and represents the servlet

<servlet-name>: This is the sub element of servlet and used to represents the name of servlet

<servlet-class>: This is the sub element of servlet and used to represents the class of servlet

<servlet-mapping>: This is the sub element of and used to map the servlet

<url-pattern>: This is the sub element of servlet-mapping and used to client side to invoke the
servlet

4.4.2
Web.xml Tags >>>
Welcome-file-list tag >>
This tag is used to specify the default page of web application if none is specified.
Example:
[code lang=”xml”]
<welcome-file-list>
<welcome-file>hello.html</welcome-file>
</welcome-file-list>
[/code]

In the above example index.jsp used as web page for web application

Session config tag >>


This tag is used to specify the session configuration parameter

Example:
[code lang=”xml”]
<session-config>
<session-timeout>
15
</session-timeout>
</session-config>[/code]
In the above example session-config tag contains another tag session-timeout which specifies the
http session timeout. The time specify in minutes.

Error page tag >>


This tag is used to specify the error occurred in the while weblogic server is responding to a HTTP
request, returns an HTML page that displays either the HTTP error code.
[code]
<error-page>
<error-code>105</error-code>
<location>/jsp/error/PageNotFound.jsp</location>
</error page> [/code]
In the above example error-page tag specify the error code as 105 and location describes the
location of the jsp page.
4.5 Deploying a Java Web Application >>>

<< Install Tomcat on Linux Mint >>


Make tomcat directory inside opt folder >>
sudo mkdir /opt/tomcat
cd /opt/tomcat

Download and extract tomcat pacakge >>


sudo wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.62/bin/apache-tomcat-9.0.62.tar.gz
sudo tar -xvf apache-tomcat-9.0.62.tar.gz

You should have following files (bold ones are directories)

bin
BUILDING.txt
conf
CONTRIBUTING.md
lib
LICENSE
logs
NOTICE
README.md
RELEASE-NOTES
RUNNING.txt
temp
webapps
work

Edit > conf/tomcat-users.xml file and add following lines >>


<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager"/>
<role rolename="manager-gui"/>

<user username="admin" password="admin123" roles="admin,admin-gui,manager,manager-


gui,manager-script"/>

Start server using following command (inside bin folder )>>


./startup.sh
Type localhost:8080 in web browser >>

Stop server using following command (inside bin folder )>>


./shutdown.sh

In our syllabus we will use netbeans IDE to start and stop the server.Before using tomcat in
netbeans make sure to shutdown server in cmd to avoid confict.

Now open our WebApplicationDemo in NetBeans IDE >>

Go to Services tab >> Servers


Right click on Apache Tomcat or TomEE and select Start >>(close any tomcat instances if
started from cmd)
Provide username and password (in our case its admin and admin123) >>

It should display web applications >>

Right click on project >> Build >> Run project >>

Run Project and Check output in browser >>

Check Servers >>


It should display our project

This is how we deploy project in tomcat using netbeans.


4.6

Servlet >>
Servlet technology is used to create a web application. It resides at server side and generates a
dynamic web page).

Servlet is a class that extends the capabilities of the servers and responds to the incoming requests.
It can respond to any requests.

Servlet is a web component that is deployed on the server to create a dynamic web page.

Web Container >>

A web container is the component of a web server that interacts with Java servlets. A web container
manages the life cycle of servlets; it maps a URL to a particular servlet

The web

container creates threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low.
Life cycle of servlet >>
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded. >>


The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
2. Servlet instance is created >>
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3. init method is invoked >>
The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet.
4. service method is invoked >>
The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once.
5. destroy method is invoked >>
The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resources.
As displayed in the above diagram, there are three states of a servlet: new, ready and end.
The servlet is in new state if servlet instance is created.

After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks.

When the web container invokes the destroy() method, it shifts to the end state.
4.7 Creating and Initializing Servlet >>
Servlet API >>

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
javax.servlet >>
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
javax.servlet.http >>
The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.
The servlet example can be created by three ways >>
• By implementing Servlet interface
• By inheriting GenericServlet class
• By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

<<Creating Servlet >>


Open our WebApplicationDemo > Click on New >> Standard Deployment
Descriptor(web.xml) >>

It will

generate web.xml file >>


New > Servlet >>

Check on Add information to deployment descriptor(web.xml) >>

check web.xml >>


Following code should be generate automatically >>
Enter follwing url in browser >>
http://localhost:8080/WebApplicationDemo/DemoServlet

This is how we create servlet.


4.8 Writing service methods >>

HttpServletRequest class methods >>

String getParameter(String name) >


returns value of parameter by name

String getLocalAddr() >


returns the Internet Protocol(IP) address of the interface on which the request was received

String getServerName() >


returns the host name of the server to which the request was sent

int getServerPort() >


returns the port number to which the request was sent

boolean isSecure() >


returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

String getContextPath() >


returns the portion of the request URI that indicates the context of the request

String getMethod() >


Returns the name of the HTTP method with which this request was made, for example, GET, POST,
or PUT.

String getPathInfo() >


returns any extra path information associated with the URL the client sent when it made this
request.

String getServletPath() >


returns the part of this request's URL that calls the servlet

<< Example >>

index.html >
<!DOCTYPE html>
<html>
<body>
<form method="post" action="DemoServlet">
Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>
</body>
</html>

web.xml >

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/DemoServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

DemoServlet.java >

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet


{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String user = request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");

String localAddress = request.getLocalAddr();


out.println("<h3> Local Address > "+localAddress+"</h3>");

String serverName = request.getServerName();


out.println("<h3> Server Name > "+serverName+"</h3>");

int portNumber = request.getLocalPort();


out.println("<h3> Port Number > "+portNumber+"</h3>");

boolean isSecure = request.isSecure();


out.println("<h3> Is using https > "+isSecure+"</h3>");
String contextPath = request.getContextPath();
out.println("<h3> Context Path > "+contextPath+"</h3>");

String method = request.getMethod();


out.println("<h3> Method Used > "+method+"</h3>");

String pathInfo = request.getPathInfo();


out.println("<h3> Path Info > "+pathInfo+"</h3>");

String servletPath = request.getServletPath();


out.println("<h3> Servlet Path > "+servletPath+"</h3>");
}
finally
{
out.close();
} } }

<< Output >>


index.html >>

DemoServlet.java >>
HttpServletResponse class methods >>
Format of http response >>

http respose header >>

PrintWriter getWriter() >


returns a PrintWriter object that can send character text to the client.

void setBufferSize(int size) >


Sets the preferred buffer size for the body of the response

void setContentLength(int len) >


Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP
Content-Length header

void setContentType(String type) >


sets the content type of the response being sent to the client before sending the respond.

boolean isCommitted() >


returns a boolean indicating if the response has been committed

int getStatus() >


gets the current status code of this response
String getHeader(String name) >
gets the value of the response header with the given name.

void setHeader(String name, String value) >


sets a response header with the given name and value

You might also like