JSP - Nine Built-in Objects - response

Posted by akumakeenta on Tue, 01 Oct 2019 01:12:04 +0200

  • The response object is an instance of the javax.servlet.http.HttpServletResponse class. Just as the server creates the request object, it also creates a client response.

  • The response object defines the interface for processing the creation of HTTP headers. By using this object, developers can add new cookie s or timestamps, HTTP status codes, and so on.
    Common methods

Serial number Method-description
1 void addCookie(Cookie cookie) adds the specified cookie to the response
2 void sendRedirect(String location) sends a temporary indirect response to the client using the specified URL
3 void setCharacterEncoding(String charset) specifies the coded set of the response (MIME character set), such as UTF-8.

Demonstration:
Registered User (Method Jump Page of Response Object)
Idea: Write a log.jsp with registration style, connect check.jsp with action attribute, check.jsp with request object to check whether the registration is successful or not. If the registration is successful, jump page to sucess.jsp with object response object method, then output jump fails.

  • response.sendRedirect("success.jsp"); the first way to jump a page: redirect, resulting in data loss
    logging.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="check.jsp" method="post">
    User name:<input type="text" name="uname"></br>
    Password:<input type="password" name="upwd"></br>
    <input type="submit" value="Sign in"></br>
    
    </form>
</body>
</html>

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <%
  String name= request.getParameter("uname");
  String pwd= request.getParameter("upwd");

  if(name.equals("zlj")&&pwd.equals("1223455678")){
	  
	 response.sendRedirect("success.jsp");//The first way to jump pages: redirect, resulting in data loss
	 // request.getRequestDispatcher("success.jsp").forward(request, response); / / page Jump second way: request forwarding, you can get data, and the address bar remains unchanged
	  
  }else
	  
	  out.println("Login failed");
  %>

</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   //Login successfully</br>
   welcome
<%
  String name=request.getParameter("uname");
   out.print(name);

%>
</body>
</html>


Enter the correct password, login display

Data loss

Topics: JSP Java Attribute