Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

RequestDispatcher and Redirect

Project Structure

index.jsp
<body>
<form action="add">
Enter 1st number : <input type="text" name="num1" /><br>
Enter 2nd number : <input type="text" name="num2" /><br>
<input type="submit" />
</form>
</body>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.controller.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bcd</servlet-name>
<servlet-class>com.controller.SqServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bcd</servlet-name>
<url-pattern>/sq</url-pattern>
</servlet-mapping>

</web-app>

AddServlet.java

public class AddServlet extends HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)


throws IOException,ServletException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));
int k=i+j;

System.out.println(i+"+"+j+"="+k);
req.setAttribute("k", k);

//PrintWriter out=res.getWriter();
//out.println(i+"+"+j+"="+k);
RequestDispatcher rd=req.getRequestDispatcher("sq");
rd.forward(req, res);

}
}

SqServlet.java
public class SqServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));

int k=(Integer)req.getAttribute("k");

System.out.println(i+"+"+j+"="+k);

PrintWriter out=res.getWriter();
out.println("Result Is : "+k*k);
}
}
HttpServletRequest and Response

Both are Interfaces. A client sends the information to the server using HttpServletRequest and receives the
information using HttpServletResponse.

sendRedirect an URL Rewriting


Project Structure: As in the last one.

AddServlet.java
public class AddServlet extends HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)


throws IOException,ServletException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));
int k=i+j;

System.out.println(i+"+"+j+"="+k);

res.sendRedirect("sq?k="+k);//URL Rewriting
}
}

SqServlet.java
public class SqServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException{
int k=Integer.parseInt(req.getParameter("k"));

PrintWriter out=res.getWriter();
out.println("Result Is : "+k*k);
}
}

//Final URL : http://localhost:8021/T01_MyApp/sq?k=4

httpSession and Cookie

Session will be given by Tomcat. Session is generally used to verify login. We use
HttpSessoin session=req.getSession();
session.setAttribute(“k”,k);
res.sendRedirect(“sq”);
session.getAttribute(“k”);
AddServlet.java
public class AddServlet extends HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)


throws IOException,ServletException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));
int k=i+j;

HttpSession session=req.getSession();
session.setAttribute("k",k);
res.sendRedirect("sq");

}
}

SqServlet.java
public class SqServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException{

HttpSession session=req.getSession();
//session.removeAttribute("k");
//if we un-comment above line then we would get error.
int k=(Integer)session.getAttribute("k");
PrintWriter out=res.getWriter();
out.println("Result(Session) Is : "+k*k);

}
}

Cookie : Whenever we send a request to the server and a server add will send us a response. In that response object,
we will have a Cookie. And then when we send the request to the sq servlet we can send the same Cookie again.
So, difference is Cookie is coming on the client side and we are again sending the Cookie to the server. E.g., getting a
token(Cookie) at a restaurent for not having change.
AddServlet.java
public class AddServlet extends HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)


throws IOException,ServletException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));
int k=i+j;

System.out.println(i+"+"+j+"="+k);

Cookie cookie=new Cookie("k",k+"");


res.addCookie(cookie);
res.sendRedirect("sq");
}
}

SqServlet.java
public class SqServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException{

int k=0;
Cookie cookies[]=req.getCookies();

for(Cookie cookie:cookies){
if(cookie.getName().equals("k"))
k=Integer.parseInt(cookie.getValue());
}

PrintWriter out=res.getWriter();
out.println("Result(Cookie) Is : "+k*k);
}
}
ServletConfig and ServletContext

To get the initial value for a servlet or for the application, e.g., if we want to specify the username and password or
any intial-setup like file-path. Then we will specify these all stuffs in web.xml in <context-param> and <init-param>
tags. The only difference is in case of <context-param> the value is shared with all the servlets in the application.

Project Structure:

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.controller.MyServlet</servlet-class>

<init-param>
<param-name>name</param-name>
<param-value>Hussain</param-value>
</init-param>

</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>Waquar</param-value>
</context-param>
<context-param>
<param-name>Phone</param-name>
<param-value>RealMe C2</param-value>
</context-param>

</web-app>

MyServlet.java
public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse


res)throws IOException{
PrintWriter out=res.getWriter();
out.print("Hi <br>");

ServletContext cxt = getServletContext();


//Method is obtained from HttpServlet
String name=cxt.getInitParameter("name");
String phone=cxt.getInitParameter("Phone");
out.println("Message from ServletContext => "+name+" :
"+phone+"<br>");

ServletConfig cfg = getServletConfig();//Method is obtained


from HttpServlet
name=cfg.getInitParameter("name");
out.println("Message from ServletConfig => "+name+"<br>");
}
}
Servlet Annotation Configuration
A servlet can be called without using web.xml configuration. In this case we will have to use annotation
@WebServlet(“url”) e.g., for AddServlet.java we will use @WebServlet(“/add”) and for SqServlet.java we will use
@WebServlet(“/sq”) as follows.

AddServlet.java
@WebServlet(“/add”)
public class AddServlet extends HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)


throws IOException,ServletException{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));
int k=i+j;

System.out.println(i+"+"+j+"="+k);

Cookie cookie=new Cookie("k",k+"");


res.addCookie(cookie);
res.sendRedirect("sq");
}
}

SqServlet.java
@WebServlet(“sq”)
public class SqServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException{

int k=0;
Cookie cookies[]=req.getCookies();

for(Cookie cookie:cookies){
if(cookie.getName().equals("k"))
k=Integer.parseInt(cookie.getValue());
}

PrintWriter out=res.getWriter();
out.println("Result(Cookie) Is : "+k*k);
}
}
Why JSP?
For the view, we should use JSP not the Servlet as we did earlier. What we did in the earlier application, we gave the
final result on the Servlet, which is not good. All the views on the client side should be done using JSP/html.
As if we have to perform some page manipulation like adding background color or a table then we will have to write
so many text on the servlet. So, it is better to use JSP.

How JSP Translates into Servlets?


Servlets run on Tomcate(Tomcat is also call servlet container). In Tomcat we can only run Servlet not JSP. So, JSP
must be getting converted into Sertvlet.
Note: Imlicit objects(request, response, session,out,pageContext,application, config, page) are given by JSP. A JSP
demo.jsp will become demo_jsp class.

JSP specific tags:


1. Scriptlet <% %> : All coding will be copied and pasted to service() method.
2. Declaration <%! %> : All coding (defining data members or member functions) will be copied and pasted
outside the service() method.
3. Directive <%@ import =”java.util.Date, java.sql” %> : That is used to write codes that are written outside the
class.
4. Expression <%= var> : gets converted into out.println(var);
JSP Tags : Scriptlet, Declaration, Directive and Expression

JSP Directive : @page, @include and @taglib


@page: When we want to import a package, it can be used.
@include: When we want to incluse some other jsp file in the current file then we can use it.
@taglib: It can be used when we are required to include some other tags. E.g., Spring provides spring specific tags, so
in order to use them we need to use @taglib.

@page : <%@ page attribute=”value” attribute=”value” ... %>


e.g., some of the attribute=”value” pair

@include :
@taglib :

Upto 2:24:01
Implicit Object In JSP
Exception Handling In JSP
Project Structure:

home.jsp
error.jsp

Skipping =>from 2:36:58 to 2:58:55 JDBC IN JSP, MVC in Servlet


JSTL – EL Part-1
MyServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse
res)throws ServletException, IOException{
String myName="Navin";
req.setAttribute("label",myName);
RequestDispatcher rd=req.getRequestDispatcher("display.jsp");
rd.forward(req, res);
}

Display.jsp
<% String name=request.getAttribute("label").toString();
out.println(name);
%>

<!-- the above scriptlet can be replace by below EL ie., Expression


Language -->
${label}

Note : in jstl, jstl-1.2.jar file can be added to the library. And some special tags can be used using
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Upto 3:37:15
Servlet Filter Theory
Skipping From 3:37:15 to 3:56:18
Login Using Servlet and JSP
Project Structure:

login.jsp
<body>
<form action="Login" method="post">
Username : <input type="text" name="uname"/><br><br>
Password : <input type="password" name="password"/><br><br>
<input type="submit" value="Login"/>
</form>
</body>

about.jsp
<body>This is Abdul Waquar...!</body>

welcome.jsp
<body>
<%
//below three lines are to prevent pages on back button press
response.setHeader("Cache-Control","no-cache, no-store, must-
revalidate");//HTTP 1.1
response.setHeader("pragma","no-cache"); //HTTP 1.0
response.setHeader("expires","0");//when we use proxy server
if(session.getAttribute("uname")==null){
response.sendRedirect("../login.jsp");
}
%>
welcome ${uname}
Click <a href="video.jsp"> here </a> to get the videos
</body>
video.jsp
<body>
<%
//below three lines are to prevent pages on back button press
response.setHeader("Cache-Control","no-cache, no-store, must-
revalidate");//HTTP 1.1
response.setHeader("pragma","no-cache"); //HTTP 1.0
response.setHeader("expires","0");//when we use proxy server

if(session.getAttribute("uname")==null){
response.sendRedirect("../login.jsp");
}
%>

<iframe width="560" height="315"


src="https://www.youtube.com/embed/-_uzpVWRlOM" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-
in-picture" allowfullscreen></iframe>
<br><br>
<form action="../Logout" method="post">
<input type="submit" value="Logout"/>
</form>

</body>

Login.java
@WebServlet("/Login")
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("hey i am in the login servlet");

String uname=request.getParameter("uname");
String password=request.getParameter("password");

if(uname.equals("waquar") && password.equals("123")){

HttpSession session=request.getSession();
session.setAttribute("uname", uname);
response.sendRedirect("jsp/welcome.jsp");
}
else{
response.sendRedirect("login.jsp");
}

}
Logout.java
@WebServlet("/Logout")
public class Logout extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

HttpSession session=request.getSession();
PrintWriter out=response.getWriter();

out.println("Logout Page"+session.getAttribute("uname"));
session.removeAttribute("uname");
session.invalidate();
try{

out.println("Logout Page"+session.getAttribute("uname"));
}catch(Exception e){
out.println(e.getMessage());
}
//response.sendRedirect("../login.jsp");
}

You might also like