-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#5_HTTPServletRequest_and_Response
68 lines (42 loc) · 2.41 KB
/
#5_HTTPServletRequest_and_Response
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
--> public void doGet(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;
// Session Management --> concept used to print the added value in this case. Data is shared from one Servlet to another
req.setAttribute("k", k);
PrintWriter out = res.getWriter();
out.println("Result is: " +k);
// To call servlet we have two methods:
// 1. Request Dispatcher (Req Dis)
// 2. Redirect (Redirect)
RequestDispatcher rd = req.getRequestDispatcher("sq");
rd.forward(req, res);
}
=================================================== Theoretical ===============================================
--> Request Disaptcher (Rd) --> Rd is used to connect two Servlet Ex: When from client side a request is made then if we have two servlets, one is website and other is
payment gateway then this Rd is used.
--> But when we want to redirect to payment gateway then Sendredirect() method is used. In this the page will say you are being
redirected.
--> In redirect two different request object is used.
==================================== URL Rewriting ==============================================================================
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddServlet extends HttpServlet
{
public void doGet(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;
// Session Management --> concept used to print the added value in this case. Data is shared from one Servlet to another
res.sendRedirect("sq?k="+k);// Hey client just go to square servlet
// --> Here we used 3. URL Rewriting. --> Another way: 1.Cookies
// 2.Session Management
// --> Session Management