JSPServlet
JSPServlet
Darshana Prasad
❑ A Document that, every time it is requested, displays on the browser exactly as it stored in
the server.
❑ It doesn’t change at all, unless if the creator changes it manually.
Darshana Prasad
❑ Web pages that are generated using scripting languages and programs interacting with a
database on the server side.
❑ Programs that add, edit, restrict, or remove data without the creator intervention.
❑ Allow the user to interact and add content.
Darshana Prasad
❑ A group of interlinked and well-structured web pages that exist on the same domain.
❑ Static Websites.
❑ Dynamic Websites.
Darshana Prasad
❑ A software application that exist on the server and runs using a web browser, through a
web page.
❑ Created using a combination of programming languages and web application frameworks.
❑ Web Apps are based on user engagement.
❑ Web apps are similar to desktop apps.
❑ They are more complicated and need more skills than websites do.
Darshana Prasad
Darshana Prasad
❑ Java Web Application can be developed by only from web related technologies.
(JSP, Servlet, HTML, CSS, Java Script, XML)
❑ Java Enterprise Application can be developed by any Java EE technologies.
(EJB, JMS + Web related technologies)
❑ Web application need a web server and Enterprise application need a Application Server to
run.
❑ Enterprise app could be a web app or desktop app or mobile app or combinations of them.
Darshana Prasad
❑ Client: A client in basically
something(web browser)
or someone(user) who
requests some resource
HTTP Request
from server.
❑ Server: A server is a
combination of a hardware
machines and a number of
softwares running on that
machine. The one and only
HTTP Response
duty of server is to serve
resources that are being
requested by the client.
Client
Server
❑ HTTP Request = Request Line + Http Headers
❑ Request Line = HTTP Method + Request URI + HTTP Version
▪ HTTP method, there are 7 methods defined in HTTP but most of
the time you will see either a GET or POST method.
Ex HTTP methods: GET, POST, HEAD, PUT, DELETE, OPTIONS,
HTTP REQUEST CONNECT
▪ Request URI, It is used to identify the resource upon which to apply
Client Server the request.
▪ Ex Request Line : GET http://www.javatpoin HTTP/1.1
❑ Http Headers, The request-header fields are used to allow
the client to pass additional information to the server
▪ Ex http Headers : Accept , Accept Language, Accept encoding,
User-Agent
❑ With browser developer options, you can find the components in an HTTP request.
❑ In chrome browser, Open the top-right Chrome menu, find tools and select Developer
Tools. (short cut key: Ctrl + Shift + i)
❑ Go to Network tab -> Headers
❑ HTTP Response = Status Line + Http Headers + Message Body
❑ Status Line = HTTP Version + Status Code + Reason Phrase
▪ HTTP Version, Ex HTTP Version : HTTP/1.1
Client Server ▪ Status Code, It is a three-digit number that indicates the result of the
request.
H
HT
ttTpP RReessppoonnssee
▪ Ex Status Codes and Description :
1xx: Information
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error
❑ Http Headers, The request-header fields are used to allow
the client to pass additional information to the server
▪ Ex http Headers : Accept-Ranges, Age , ETag, Location
❑ Message Body, HTML Codes or Error Codes
❑ With browser developer options, you can find the components in an HTTP request.
❑ In chrome browser, Open the top-right Chrome menu, find tools and select Developer
Tools. (short cut key: Ctrl + Shift + i)
❑ Go to Network tab -> Headers
❑ Servlet can be described in many ways, depending on the context.
▪ Servlet is a technology which is used to create a web application.
▪ Servlet is an API that provides many interfaces and classes including documentation.
▪ Servlet is an interface that must be implemented for creating any Servlet.
▪ 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.
▪ TomEE Application Server has both Servlet container and EJB container.
Servlet Container
• The servlet container is the part of web server which can be run in a separate process.
• Servlet Container communicates between client Browsers and the servlets.
• Servlet Container managing the life cycle of servlet. Servlet container loading the servlets into memory, initializing and
invoking servlet methods and to destroy them. There are a lot of Servlet Containers like Jboss, Apache Tomcat, WebLogic
etc.
Java Servlet Life Cycle
Java Servlet life cycle consists of a series of events that begins when the Servlet container loads Servlet, and
ends when the container is closed down Servlet. A servlet container is the part of a web server or an application
server that controls a Servlet by managing its life cycle.
The Servlet container running a Servlet’s init () method, which initializes Servlet, once in the Servlet life cycle, after
loading the Servlet and create a Servlet object. The init method definition looks like this:
// Initialization code...
}
The service () method
The Servlet container running a Servlet’s init () method, which initializes Servlet, once in the Servlet life cycle, after
loading the Servlet and create a Servlet object. The init method definition looks like this:
The container runs the Servlet service () method for each request from a client, a web browser. The service method
definition looks like this:
}
The destroy () method
The Servlet container running a servlet’s destroy () method once in a lifetime to close the Servlet. The destroy method
definition looks like this:
The destroy ( ) method waits until all threads started by the service () method before terminating the execution of the
servlet.
Note– The init() and destroy() method only once called during its servlet life cycle.
Architecture Diagram of Servlet Life Cycle:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/my-first-servlet")
public class MyFirstServlet extends HttpServlet {
public MyFirstServlet() {
// Default Constructor
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("This is Servelet doGet method...");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("This is Servelet doPost method...");
}
}
❑ You need to pass some information from your browser to web server and ultimately to
your backend program.
❑ Servlets handles form data parsing automatically using the following methods
depending on the situation.
getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters
in the current request.
❑ url:
http://localhost:8080/jeecrudapp?name=Tharanga&[email protected]
❑ Servlet: DashboardServlet
❑ Http Method: GET
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
request.setAttribute("name", "Tharanga");
out.println(request.getAttribute(« name"));
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it
may be servlet, jsp or html file.
Example – Servlet 01
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to
manage the web application if any specific content is modified from time to time.
EXAMPLE – web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("Name: "+str);
out.print(" value: "+config.getInitParameter(str));
Servlet with Annotation (feature of servlet3):
Annotation represents the metadata. If you use annotation, deployment descriptor (web.xml file) is not required.
1.@WebServlet("/Simple")
Homework!
Client JSP
HTTP Response
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("dashboard.jsp").forward(req, resp);
}
❑ In JSP, java code can be written inside the JSP page using the scripting elements.
▪ Expressions
– Format: <%= expression %>
▪ Scriptlets
– Format: <% script %>
▪ Declarations
– Format: <%! declaration %>
❑ Code placed within expression tag is written to the output stream of the response
❑ Syntax:
<%= expression %>
❑ Example:
<html>
<body>
<%= “Hello world…” %>
</body>
</html>
❑ Syntax:
<% java source code %>
❑ Example:
<html>
<body>
<% out.print(“Hello world…”); %>
</body>
</html>
❑ Declarations are used to define methods & instance variables
❑ Syntax:
<%! Statement %>
❑ Example:
<html>
<body>
<%! int data=60; %>
<%= “Value is: “ + data %>
</body>
</html>
❑ JSP Implicit Objects are also called pre-defined variables.
❑ We can use implicit objects in JSP directly in Scriptlets that goes in service method.
❑ However we can’t use JSP implicit objects in JSP declaration because that code will go at
class level.
❑ There are 9 JSP implicit objects. These objects are created by the web container that are
available to all the JSP pages.
JSP vs Servlet
<%
int price = Integer.parseInt(request.getParameter("itemPrice"));
int qty = Integer.parseInt(request.getParameter("itemQty"));
tot = price*qty;
LocalDateTime myObj = LocalDateTime.now();
out.println("Date - "+myObj);
%><!-- Scriptlets -->
</body>
❑ An instance of JspWriter.
❑ Writes statements to the page.
❑ The java way to display text on the webpage.
❑ Displaying dynamic data
❑ Example:
<html>
<body>
<% out.print("implicit objects"); %>
</body>
</html>
❑ Instance of HttpServletRequest
❑ Example:
<html>
<body>
<%= request.getAttribute("a") %>
</body>
</html>
❑ Instance of HttpServletResponse
Send response to client
❑ Send response back to client JSP1 Client
❑ response.sendRedirect(“url”)
Send response to
client
JSP1 JSP2 Client
❑ Example: Redirect
to jsp2
<html>
<body>
<% response.sendRedirect("dashboard2.jsp"); %>
</body>
</html>
Request 1
❑ Instance of HttpSession Response 1
❑ Retrieve and set the session attributes Request 2 Client
in JSP Web App
Response 2
❑ Remember the client across multiple
requests
❑ Example: SESSION
<html>
<body>
<% session.setAttribute("username", "kamal"); %>
</body>
</html>
❑ session.invalidate() can be use to invalidate a session.
❑ config: Instance of ServletConfig
▪ The config object is created by the web container
for each JSP page.
❑ application: instance of servletContext Servlet context
▪ The application object is created by the web
container at time of deploying the project
❑ In servlet 3.0 many of the web.xml parts are optional. These configurations can be done
via annotations (@WebServlet, @WebListener)
❑ Right click on project folder ->
JavaEE tools -> Generate
Deployment Descriptor Stub
❑ This will add the web.xml file under
the WEB-INF folder.
❑ In web.xml
❑ Example
<web-app>
<servlet>
<servlet-name>dashboardServlet</servlet-name>
<jsp-file>/dashboard.jsp</jsp-file>
<init-param>
<param-name>dbname</param-name>
<param-value>my-database</param-value>
</init-param>
</servlet>
<context-param>
<param-name>dbpassword</param-name>
<param-value>root</param-value>
</context-param>
</web-app>
❑ In dashboard.jsp
❑ Example
<html>
<body>
<%= config.getInitParameter("dbname") %>
<%= application.getInitParameter("dbpassword") %>
</body>
</html>
❑ This object is an actual reference to the instance of the page.
❑ It can be thought of as an object that represents the entire JSP page.
Header page
<jsp:include page=”/header.jsp”/>
header.jsp
Main Page
Footer page
<jsp:include page=”/footer.jsp”/>
main.jsp footer.jsp
❑ Used to generate the appropriate response to the error condition.
❑ This object can be used to print the exception.
❑ But it can only be used in error pages.
❑ Example:
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occurred:<%= exception %>
</body>
</html>
❑ Every object created in a JSP page will have a scope.
❑ Object scope in JSP is segregated into four parts and they are page, request, session and
application.
most
visible
application
session
pageContext
request
page
least
visible
❑ The JSP directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
▪ page directive
▪ include directive
▪ taglib directive
errorPage Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.
import Specifies a list of packages or classes for use in the JSP as the
Java import statement does for Java classes.
info Defines a string that can be accessed with the servlet's getServletInfo()
method.
session Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored Specifies whether or not EL expression within the JSP page will be
ignored.
<%
MyBean m = new MyBean();
%>
OR
<%
m.setName(“ali”);
%>
OR
<%
String name = m.getName();
out.println(name);
%>
OR
❑ Format
<jsp:forward page=“one.jsp" />
❑ A web container/servlet engine in one which helps the server to communicate with
servlet and servlets takes birth and died in a web container.
❑ Whenever a request comes from client to server the server sends that request to web
container and web container invokes either a get or a post method written on servlet.
❑ Whenever a http request for dynamic resource came to the server, the server send that
http request to container.
❑ The container converts the http request into valid request and response objects to
communicate to servlet.
❑ response object is responsible for getting back the response from servlet to container.
❑ Every time a new request came to the container it generates a new thread per request
and new request and response object for every new request.
❑ When the response is got back by the container the request/response objects are
destroyed by the container itself.
❑ Ex: Tomcat, Jetty
Load .class file Call Default Constructor Call init()
/login
Login Servlet
http://localhost:8080/login
Welcome.html
Http Request Servlet Request HttpServletRequest
Servlet
HttpServletResponse
thread
doGet() / doPost()
Servlet Response
request
response Servlet
❑ The container finds the correct servlet, based on the URL in the request, creates a
thread for that request, and passes the request and response objects to the servlet
thread.
Servlet
Servlet Container
thread
request response
❑ The container calls the servlet’s service() method. Depending on the type of request,
the service() method typically calls either the doGet() or doPost() method.
Servlet
Servlet Container
thread
Service()
request
response
❑ The doGet() method generates the dynamic page and stuffs the content into the
response object.
Servlet
Servlet Container
thread
response Service()
doGet()
❑ The thread completes, the container converts the response object into an HTTP
response, sends it back to the client, then deletes the request and response objects.
request
X
response
❑ Communication Support : Everything that happens to a servlet the container is
responsible for that. It provide an communicative interface between server and the
servlets.
❑ Lifecycle Management Support : Servlet have a number of methods to initialize it,
provide services and destroy it. And all those methods are invoked by the container
from the birth to the death of an servlet.
❑ Multi-threading support : For every request that comes in for the servlet the container
creates a separated thread and execute service method as per client request.
❑ Security Handling : As the requests are always coming through the container, we can put
security constraints in container to stop a invalid request being processed.
❑ JSP Support
❑ The welcome-file-list element of web-app, is used to define a list of welcome files. Its
sub element is welcome-file that is used to define the welcome file.
❑ A welcome file is the file that is invoked automatically by the server, if you don't specify
any file name.
❑ If none of these files are found, server renders 404 error.
❑ If you have specified welcome-file in web.xml, and all the files index.html, index.htm
and index.jsp exists, priority goes to welcome-file.
❑ If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file
then index.htm and at last index.jsp file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Project01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>addServlet</servlet-name>
<servlet-class>com.nibm.kandy.hd201.webapplication01.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServlet</servlet-name>
<url-pattern>add-servlet</url-pattern>
</servlet-mapping>
</web-app>
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to
Bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit()
method.
6. Request Processing by calling
jspService() method.
7. Destroying by calling jspDestroy()
method.