AOOP-Lect 12-Servlet
AOOP-Lect 12-Servlet
Servlets
1 Practice More
By Zohair Ahmed
Servlet
▸Servlet is server side technology which is used to:
- Handle Client request
- Process the request
- Generate Dynamic response
▸Client Request Server Handle
- At Server Side java has container
- Servlet
- JSP
- Security etc.
▸Web Server
- Apache tomcat
- Glassfish
- Jetty
By Zohair Ahmed
Servlet
Eclipse
It sends exactly the same response It may generate different HTML for
for every request. each of the request.
The content is only changed when The page contains "server-side"
someone publishes and updates code which allows the server to
the file (sends it to the web server). generate the unique content when
the page is loaded.
By Zohair Ahmed
Servlet Hierarchy
By Zohair Ahmed
HTTP Servlet
By Zohair Ahmed
Download Tomcat 10.1
JAVA EE vs. Jakarta
▸Apache Tomcat®
Direct Link:
6 https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.16/bin/apache-tomcat-10.1.16-windows-x64.zip
By Zohair Ahmed
Configure Tomcat
2 3
1
5 6
4
By Zohair Ahmed
Create Web Project in Eclipse
Must Installed JAVA EE packages (e.g. Web etc.)
1
4
3
2
After Every screen click NEXT, don’t change any setting – Web Module Version should be 5.0
8
By Zohair Ahmed
Create Servlet
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
}
}
By Zohair Ahmed
Update Web.xml
Deployment Descriptor, Remove all code except <web-app> tag.
<servlet-mapping>
<servlet-name>ServletName</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
10
By Zohair Ahmed
Run Server
▸Localhost:8080/webapp/index
11
By Zohair Ahmed
Web Content Display
package com.java.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
By Zohair Ahmed
Task
▸Create Two Servlet
- Login
- Register
▸Create Two URL and these two URL print different Servlet Get Request
13
By Zohair Ahmed
Create Two Servlet
public class MyServlet1 extends HttpServlet { public class MyServlet2 extends HttpServlet {
@Override @Override
protected void doGet(HttpServletRequest req, protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws HttpServletResponse resp) throws ServletException,
ServletException, IOException { IOException {
System.out.println("MyServlet1 Console"); System.out.println("MyServlet2 Console");
PrintWriter pw = resp.getWriter(); PrintWriter pw = resp.getWriter();
pw.print("MyServlet1 Web"); pw.print("MyServlet2 Web");
} }
} }
14
By Zohair Ahmed
Web.xml
<web-app>
<servlet>
<servlet-name>map1</servlet-name>
<servlet-
class>com.java.servlet.MyServlet1</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>map1</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>map2</servlet-name>
<servlet-
class>com.java.servlet.MyServlet2</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>map2</servlet-name>
<url-pattern>/index2</url-pattern>
</servlet-mapping>
15 </web-app>
By Zohair Ahmed
Servlet Life Cycle
▸Loading and Instantiation
- When server is started, servlet class is loading in the memory and servlet object is
created.
▸Initialization
- Servlet object will be initialized by invoking init() method.
▸Request Handling
- It will handle or serve the client request by invoking service() method. It use threads
by multiple request.
▸Destroy
- When the server is shutdown destroy() method will be executed and servlet object
will be deleted
16
By Zohair Ahmed
<html>
Servlet Annotation <head>
<title>Web App</title>
</head>
No Need of web.xml in latest version: The version 3.0 or above <body>
<a href="link">Click for Servlet</a>
</body>
▸@webServlet </html>
package com.java.servlet;
▸@webFilter import java.io.IOException;
import java.io.PrintWriter;
▸@webListener import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
▸@webMultipartConfig import
import
jakarta.servlet.http.HttpServletRequest;
jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;
@WebServlet("/link")
public class MyServlet3_annot extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
Make a html file under project throws ServletException, IOException {
//System.out.println("MyServlet2 Console");
name src/webapp PrintWriter pw = resp.getWriter();
pw.print("MyServlet3 using Web Annot. No web.xml");
}
}
17
By Zohair Ahmed
HttpServletRequest, HttpServletResponse
▸HttpServletRequest, HttpServletResponse both are interface.
▸Request object responsible for sending Requests
▸Response object responsible for Response back
▸There are many methods for request and response pipeline.
▸HttpServletRequest ▸HttpServletResponse
▸getParameter(String name) ▸getwriter()
▸getCookies() ▸sendRedirect(String Location)
▸getMethod() ▸sendError(int code, String Messsage)
▸getSession(Boolean ) ▸And many more…….
18
By Zohair Ahmed
HTML Form Post and Servlet Print on Web
package com.java.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
<!DOCTYPE html> import jakarta.servlet.annotation.WebServlet;
<html> import jakarta.servlet.http.HttpServlet;
<head> import jakarta.servlet.http.HttpServletRequest;
<meta charset="UTF-8"> import jakarta.servlet.http.HttpServletResponse;
<title>Student Info Form</title>
</head>
<body> @WebServlet("/submitform")
<div style="text-align:center;"> public class stdinfo_servlet extends HttpServlet {
<h2>Student Info Form</h2> @Override
<form action="submitform" method="post"> protected void service(HttpServletRequest req,
Name: <input type=" text" name="std_name" /> <br /><br /> HttpServletResponse resp) throws ServletException, IOException
Class: <input type="text" name="std_class" /> <br /><br /> {
<input type="submit" value="Save Records" /> <br /> String std_name = req.getParameter("std_name");
</form> String std_class = req.getParameter("std_class");
</div> PrintWriter pw = resp.getWriter();
</body> pw.print("Student Name: " + std_name);
</html> pw.print("Student Class: " + std_class);
}
}
19
By Zohair Ahmed
Send Redirect Method
Request Dispatcher
Include Vs. Forward
20
By Zohair Ahmed
Send Redirect()
▸HttpSevletResponse sendredirect();
▸In HTML form has one textbox for searching and direct search in Google using query String
▸Also, sendredirect change the URL for external Redirection.
21
By Zohair Ahmed
Request Dispatcher – Go to Welcome Page if Login
▸RequestDispatcher rd = req.getRequestDispatcher("/welcome.html");
▸rd.forward(req, resp);
▸It cannot change the URL
<!DOCTYPE html> @WebServlet("/submitloginform")
<html> public class login extends HttpServlet {
<head>
<meta charset="UTF-8"> @Override
<title>Login Form</title> protected void service(HttpServletRequest req,
</head> HttpServletResponse resp) throws ServletException, IOException {
<body>
<div style="text-align:center;"> String user_name = req.getParameter("user_name");
<h2>Student Login Form</h2>
String user_password = req.getParameter("user_password");
<form action="submitloginform" method="post">
User Name: <input type=" text" name="user_name" />
if (user_name.equals("zohair") && user_password.equals("123"))
Password: <input type="text" name="user_password" />
<input type="submit" value="Login" /> {
</form> RequestDispatcher rd = req.getRequestDispatcher("/welcome.html");
</div> rd.forward(req, resp);
</body> }}
</html> }
22
By Zohair Ahmed
Request Dispatcher – Go to Error Page if Invalid Login
if (user_name.equals("zohair") && user_password.equals("123")) {
RequestDispatcher rd = req.getRequestDispatcher("/welcome.html");
rd.forward(req, resp);
} If not set print html source code
else {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.print("<h3 style='color:red;'>Invalid UserName and Password<h3>");
RequestDispatcher rd = req.getRequestDispatcher("/login.html");
rd.include(req, resp);
}
Use Include for response page and
print message
23
By Zohair Ahmed
Output- URL Not Changing (Login/Invalid)
24
By Zohair Ahmed