[go: up one dir, main page]

0% found this document useful (0 votes)
45 views43 pages

Chapter-7 Servlet and JSP

The document provides an overview of Servlets and JavaServer Pages (JSP), including their definitions, lifecycle, and how they handle HTTP requests and responses. It also discusses the advantages of using Servlets, the differences between Servlets and JSP, and introduces Java web frameworks. Additionally, it includes examples of writing Servlet programs and handling form data in web applications.

Uploaded by

14depace
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)
45 views43 pages

Chapter-7 Servlet and JSP

The document provides an overview of Servlets and JavaServer Pages (JSP), including their definitions, lifecycle, and how they handle HTTP requests and responses. It also discusses the advantages of using Servlets, the differences between Servlets and JSP, and introduces Java web frameworks. Additionally, it includes examples of writing Servlet programs and handling form data in web applications.

Uploaded by

14depace
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/ 43

Servlets

and Java Server


pages (8Hrs.)
Chapter - 7
Contents
7.1. Web Container, Introduction to Servlets, Life cycle of servlets, The servlet
APIs, Writing Servlet Programs, Reading Form Parameters, Processing Forms,
Handling HTTP Request and Response (GET / POST Request), Database
Access with Servlets, Handling Cookies and Session.
7.2. Servlet vs JSP, JSP Access Model, JSP Syntax (Directions, Declarations,
Expression, Scriplets, Comments), JSP Implicit Objects, Object Scope,
Processing Forms, Database Access with JSP.

7.3. Introduction to Java Web Frameworks

11/18/2021 Er. Jeewan Rai 2


•JSP = Front End (.jsp)

•Servlet = Code Behind File (.java)


11/18/2021 Er. Jeewan Rai 3

Servlets
• Servlet technology is used to create a web application (resides at server
side and generates a dynamic web page).

• Servlet technology is robust and scalable because of java language. Before


Servlet, CGI (Common Gateway Interface) scripting language was common
as a server-side programming language.

• There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
11/18/2021 Er. Jeewan Rai 4

What is a Servlet?
• 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.
11/18/2021 Er. Jeewan Rai 5

Working of Servlet
11/18/2021 Er. Jeewan Rai 6
Advantages of Servlet
• Better performance: because it creates a thread for each
request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
• Secure: because it uses java language.

11/18/2021 Er. Jeewan Rai 7


Servlet Life Cycle
https://www.javatpoint.com/life-cycle-of-a-servlet

11/18/2021 Er. Jeewan Rai 8

Servlet Life Cycle


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. It is the life
cycle method of the javax.servlet.Servlet interface.
4) service() method is invoked: The web container calls the service method each time
when request for the servlet is received.
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 resource for example memory, thread etc
public void destroy()
11/18/2021 Er. Jeewan Rai 9

Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces and
classes for servlet api.

• 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.

• The javax.servlet.http package contains interfaces and classes that are


responsible for http requests only.
11/18/2021 Er. Jeewan Rai 10

Handling HTTP Request and Response (GET /


POST Request),
POST Method
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
GET Method
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

11/18/2021 Er. Jeewan Rai 11

Writing Servlet import java.io.*;


import javax.servlet.*;
import javax.servlet.http.*;
Programs // Extend HttpServlet class
public class HelloWorld extends HttpServlet {
<servlet>
private String message; <servlet-name>helloworld</servlet-name>
<servlet-class>HelloWorldServlet</servlet class>
public void init() throws ServletException { </servlet>
// Do required initialization
message = "Hello World"; <servlet-mapping>
} <servlet-name>helloworld</servlet-name>
<url-pattern>/welcome</url-pattern> </servlet-mapping>
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException { </web-app>
web.xml
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.

PrintWriter out = response.getWriter(); out.println("<h1>" + message +


"</h1>"); }
https://www.tutorialspoint.com/servlets/servlets-first-exa
<web-app>
mple.htm
{ // do nothing.
HelloWorld.java
public void destroy()
11/18/2021 Er. Jeewan Rai 12
https://www.javatpoint.com/steps-to-create-a-servlet-using-tomcat-server }

Reading Form Parameters,


• getParameter() − You call request.getParameter() method to get the value of a
form parameter. e.g. TextBox.
<input type="text" name="username"/>
String username = request.getParameter("username");

• getParameterValues() − Call this method if the parameter appears more than


once and returns multiple values, e.g. checkbox.
<input type="checkbox" name="language" value="english" />English
<input type="checkbox" name="language" value="french" />French

String languages[] = request.getParameterValues("language");

• getParameterNames() − Call this method if you want a complete list of all


parameters in the current request.

Er. Jeewan Rai 13

handle HTML form data with Java Servlet

• To create a form in HTML we need to use the following tags:


• <form>: to create a form to add fields in its body.

• <input>, <select>, <textarea>…: to create form fields like text


boxes, dropdown list, text area, check boxes, radio buttons,… and
submit button.

• To make the form works with Java servlet, we need to specify the
following attributes for the <form> tag:

• method=”post”: to send the form data as an HTTP POST request


to the server. Generally, form submission should be done in HTTP
POST method.

• action=”URL of the servlet”: specifies relative URL of the servlet


which is responsible for handling data posted from this form.
11/18/2021 Er. Jeewan Rai 14

handle HTML or JSP form


data with Java Servlet
<form name="loginForm" method="post"
action="loginServlet">
Username: <input type="text" name="username"/>
<br/>
Password: <input type="password" name="password"/>
<br/>
<input type="submit" value="Login" />
</form>

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// code to process the form...


String username = request.getParameter("username");

System.out.println("username: " + username);

https://mail.codejava.net/java-ee/servlet/handling-html-form-data-with-java-servlet
11/18/2021 Er. Jeewan Rai 15

JSP (JavaServer Pages)


• a technology for developing Webpages that supports dynamic
content. • This helps developers insert java code in HTML pages by
making use of
special JSP tags, most of which start with <% and end with %>. 11/18/2021 Er.
Jeewan Rai 16

JSP Lifecycle
• A JSP life cycle is defined as the process from its creation till the
destruction.
• This is similar to a servlet life cycle with an additional step which is required
to compile a JSP into servlet.
• The following are the paths followed by a JSP −
• Compilation
• Initialization
• Execution
• Cleanup

11/18/2021 Er. Jeewan Rai 17

JSP syntax
1.Declaration Tag :-It is used to declare variables.
Syntax:- <%! Dec var %>
Example:- <%! int var=10; %>
2.Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions. Syntax:- <% java code %>
3.JSP Expression :- It evaluates and convert the expression to a
string. Syntax:- <%= expression %>
Example:- <% num1 = num1+num2 %>
4.JAVA Comments :- It contains the text that is added for information which has to be
ignored.
Syntax:- <% -- JSP Comments %>
11/18/2021 Er. Jeewan Rai 18

Process of Execution
• Create project folder structure.

• Create html page from where


request will be sent to server
e.g. try.html or try.jsp
• To handle to request of user next is

to create .java file Eg. Try.java

• Create XML file e.g. my.xml.

• Start Tomcat

• Run Application
11/18/2021
https://www.geeksforgeeks.org/introduction Er. Jeewan Rai -to-jsp/ 19
Example of “Hello World”
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1"> <title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>

demo.jsp

11/18/2021 Er. Jeewan Rai 20

Introduction to Java Web Frameworks • Frameworks


are tools with pre-written code, act as a template or skeleton,

which can be reused to create an application by simply filling with your


code as needed which enables developers to program their application with

no overhead of creating each line of code again and again from scratch.

• most of the Java frameworks are free and open-source.

• E.g. Spring, Struts, Play

11/18/2021 Er. Jeewan Rai 21

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Login</title>
</head>
<body>
<form name="index" action="LoginServlet" method="get">
Username<input type="text" name="user"><!-- comment -->
Password<input type="password" name="pass"><!-- comment -->
<input type="submit" value="Login"><!-- comment -->
</form>
</body>
11/18/2021 Er. Jeewan Rai 22 >

WEB-INF/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>Login</servlet-name>
<servlet-class>controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

11/18/2021 Er. Jeewan Rai 23


package controller;
import javax.servlet.http.*;

import java.io.IOException;
public class LoginServlet extends HttpServlet {
import java.io.PrintWriter;
protected void doGet(HttpServletRequest request, HttpServletResponse
import javax.servlet.*;
response) throws ServletException, IOException { String user = request.getParameter("user");
response.setContentType("text/html"); String pass = request.getParameter("pass");

try(PrintWriter out = response.getWriter()){ out.println("Username: " + user);

String user = request.getParameter("user").toString();


if(user == "jeewan" && pass =="jeewan"){
String pass = request.getParameter("pass").toString();
response.sendRedirect("welcome.jsp");
if(user.equals("jeewan") && pass.equals("jeewan")){ }
response.sendRedirect("welcome.jsp"); }
}
else
}
out.println("Password does not match.");

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException { }
response.setContentType("text/html;charset=UTF-8");

try(PrintWriter out = response.getWriter()){


}

Source Packages/LoginServlet.java
11/18/2021 Er. Jeewan Rai 24 }
11/18/2021 Er. Jeewan Rai 25

You might also like