0% found this document useful (0 votes)
33 views86 pages

JSPServlet

Uploaded by

rukmaldmt
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)
33 views86 pages

JSPServlet

Uploaded by

rukmaldmt
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/ 86

❑ Document Written using Hypertext Markup Language.

❑ It may contains texts, graphics, hyperlinks, and many other resources.


❑ Hypertext is a text that contains hyperlinks that lead to other documents.
❑ Hyperlink is a text, word, sentence, button, icon, sometimes even a picture, when you click
or hover on it, you will be directed to another web page.
❑ We can access a web page by entering its URL address using a web browser.

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 init() method:


•The service () method
•The destroy () method
The init() 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:

public void init(ServletConfig config) throws ServletException {

// 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:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{

}
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:

public void destroy() {


// Finalization code...

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.

getParameter() − You call request.getParameter() method to get the value of a form


parameter.

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

❑ Read parameters in DashboardServlet doGet()

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


String name = req.getParameter("name");
String email = req.getParameter("email");

resp.getWriter().println("Name: "+name+ "<Br>" + "Email: "+ email);


}
RequestDispatcher in Servlet

public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or
HTML file) on the server.

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

protected void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
int price = Integer.parseInt(request.getParameter("itemPrice"));
int qty = Integer.parseInt(request.getParameter("itemQty"));
response.sendRedirect("secondOne?total="+(price*qty));
}
Example – Servlet 02

protected void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(request.getParameter("total"));
}
ServletConfig Interface
This object can be used to get configuration information from web.xml file.

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!

Cookies and HTTPSession


for login and logout
❑ Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based
applications.
❑ JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.
❑ Java Server Pages are HTML pages embedded with snippets of Java code.
❑ The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or JSP.
❑ The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.

2. public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.
Servlet

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.

❑ Types of 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>

▪ Note: Do not end statement with semicolon (;)


❑ In JSP JAVA code can be written inside the JSP page using Scriplet tag

❑ 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

<body bgcolor="brown"> protected void service(HttpServletRequest


<h1>JSP Page</h1> request, HttpServletResponse response) throws
<% ServletException, IOException {
int price = int price =
Integer.parseInt(request.getParameter("itemPric Integer.parseInt(request.getParameter("itemPr
e")); e"));
int qty = int qty =
Integer.parseInt(request.getParameter("itemQty" Integer.parseInt(request.getParameter("itemQt
)); ));
out.println("Total - "+price*qty); PrintWriter out = response.getWriter();
%> out.println("<HTML><BODY bgcolor=yellow>");
</body> out.println("Total - "+price*qty);
<body bgcolor="brown">
<h1>JSP Page</h1>

<%@page import = "java.time.LocalDateTime" %> <!-- Directive -->

<%! int tot = 0; %> <!-- Declarations -->

<%
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 -->

Total - <%= tot %><!-- Expressions -->

</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

JSP 1 JSP 2 JSP 3 JSP 4

config config config config


❑ This is the configuration file of web applications in java. It instructs the servlet container
(tomcat for ex.) which classes to load, what parameters to set in the context, and how
to intercept requests coming from browsers.

❑ There you specify:


1. what servlets (and filters) you want to use and what URLs you want to map them to
2. listeners - classes that are notified when some events happen (context starts, session
created, etc.)
3. configuration parameters (context-params)
4. error pages, welcome files
5. security constraints

❑ 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 Within all pages belonging to same


application application

Only from pages belonging to same session


session as the one in which they were created

Only within pages processing the request


request in which they are created

Objects may be accessed only within pages


Least visible page
where they are created
❑ It is used for accessing page, request, application and session attributes.

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.

❑ There are three types of directives:

▪ page directive
▪ include directive
▪ taglib directive

❑ <%@ directive attribute="value" %>


❑ Defines attributes that apply to an entire JSP page
❑ Syntax:
<%@ page attribute=“value” %>

❑ Attributes : import, contentType, extends, info, buffer, language, autoFlush, session,


pageEncoding, errorPage, isErrorPage
Attribute Purpose
buffer Specifies a buffering model for the output stream.

autoFlush Controls the behavior of the servlet output buffer.

contentType Defines the character encoding scheme.

errorPage Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.

isErrorPage Indicates if this JSP page is a URL specified by another JSP


page's errorPage attribute.

extends Specifies a superclass that the generated servlet must extend

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.

isThreadSafe Defines the threading model for the generated servlet.

language Defines the programming language used in the JSP page.

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.

isScriptingEnabled Determines if scripting elements are allowed for use.


❑ The import attribute is used to import class, interface or all the members of a package.
It is similar to import keyword in java class or interface.

❑ Example of import attribute


❑ The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.
❑ The default value is "text/html;charset=ISO-8859-1".
❑ Example of import attribute
❑ The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.

❑ Example of import attribute


❑ The isErrorPage attribute is used to declare that the current page is the error page.
❑ Example of isErrorPage attribute
❑ The include directive is used to include the contents of any resource it may be jsp file,
html file or text file.
❑ Syntax:
<%@ include file=“value” %>
Advantage of Include directive: Code Reusability
❑ Example:
❑ To work with JavaBeans
▪ <jsp:useBean />
▪ <jsp:setProperty />
▪ <jsp:getProperty />

❑ To include resources at request time


▪ <jsp:include />

❑ To forward request to anther JSP or Servlet


▪ <jsp:forward />
❑ Bean is a Java Class.
❑ It may have a number of private properties which can be read or written.
❑ It may have a number of public "getter" and "setter" methods for the properties.
❑ It should be serializable and that which can implement the Serializable interface.
❑ It provides a default, no-argument constructor.
❑ jsp:useBean is being equivalent to building an object in scriptlet

<%
MyBean m = new MyBean();
%>

OR

<jsp:useBean id = “m” class=“vu.MyBean ”/>


❑ jsp:setProperty is being equivalent to following code of scriptlet

<%
m.setName(“ali”);
%>

OR

<jsp:setProperty name = “beanName” property = “name” value=“ali” />


❑ jsp:getProperty is being equivalent to following code of scriptlet

<%
String name = m.getName();
out.println(name);
%>

OR

<jsp:getProperty name = “beanName” property= “name” />


❑ The jsp:include action tag is used to include the content of another resource it may be
jsp, html or servlet.
❑ The jsp:include tag can be used to include static as well as dynamic pages.
❑ Code reusability : We can use a page many times such as including header and footer
pages in all pages. So it saves a lot of time.

<jsp:include page = “one.jsp” flush= “true” />


❑ The jsp:forward action tag is used to forward the request to another resource it may be
jsp, html or another resource.

❑ 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

Http Response Service()


Servlet Response

doGet() / doPost()

Servlet Response

Client Web Servlet Container


Server Note: If servlet container cannot find the servlet for given URL 404 Error passes back as Servlet Response
❑ When a user requests a resource that has a URL to a servlet, instead of a static page, the
Web Server hands the request not to the servlet itself, but to the Container in which the
servlet is deployed.
❑ The container creates two objects:
▪ HttpServletRequest
▪ HttpServletResponse Web Server Servlet Container

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.

Web Server Servlet Container

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.

You might also like