Detailed usage of request and response in JSP, requestresponse

Source: Internet
Author: User

Detailed usage of request and response in JSP, requestresponse

Detailed description of request and response usage in JSP

Summary:

Before learning these two objects, we should have a basic understanding of the http protocol. If you are not clear about the http protocol, see my introduction to the http protocol. In fact, most requests and response are used for http operations.

Introduction to request objects

We will first introduce the request object:

We know that the http protocol defines the format of the Request Server:

Request Line
Request Header
Space
Request body (no request body for get requests)

Well, here we will not introduce it in detail. We only need to read a few applications and there is no difficulty:

Application 1 obtains the Request Header

/*** Get http Request Header * String getHeader (String name), applicable to single-value headers * int getIntHeader (String name ), applies to single-value int type request headers * long getDateHeader (String name), applies to single-value millisecond type request headers * Enumeration <String> getHeaders (String name ), applicable to multi-value request headers ***/public class CServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String ip = request. getRemoteA Ddr (); // obtain the IP address String method = request. getMethod (); // obtain the request method System. out. println (ip); System. out. println (method); getLiuLanQi (request); protectMethod (request, response);} // anti-leech public void protectMethod (HttpServletRequest request, HttpServletResponse response) {String url = request. getHeader ("referer"); System. out. println (url); if (url! = Null & url. inclusignorecase (" http://localhost:8080/day10/MyHtml.html ") {System. out. println ("hi");} else {response. setStatus (302); response. setHeader ("Location", "/day10/MyHtml.html"); System. out. println ("redirection") ;}// determines the browser type public void getLiuLanQi (HttpServletRequest request) {String user = request. getHeader ("User-Agent"); if (user! = Null) {String userNoC = user. toLowerCase (); if (userNoC. contains ("chrome") {System. out. println ("browser type: Google");} else if (userNoC. contains ("firefox/") {System. out. println ("browser type: Firefox");} else {System. out. println ("browser type: IE") ;}} else {System. out. println ("null ");}}}

APP 2 get URL path

/*** Get the request URL http://localhost:8080/day10_2/AServlet ? Username = xxx & password = yyy> String getScheme (): Get protocol, http> String getServerName (): Get server name, localhost> String getServerPort (): Get server port, 8080> ***** String getContextPath (): Get the project name,/day10_2> String getServletPath (): Get the Servlet Path,/AServlet> String getQueryString (): Get the parameter section, that is, the part after the question mark. Username = xxx & password = yyy> String getRequestURI (): Get the request URI, which is equal to the project name + Servlet Path. /Day10_2/AServlet> String getRequestURL (): Get the request URL, which is equal to the entire request path without parameters. http://localhost:8080/day10_2/AServlet * **/Public class DServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println (request. getScheme (); System. out. println (request. getServerName (); System. out. println (request. getServerPort (); System. out. println (request. getContextPath (); System. out. println (request. getServletPath (); System. out. println (request. getQueryString (); System. out. println (request. getRequestURI (); System. out. println (request. getRequestURL ());}}

APP 3 GET Request Parameters

/***** Request parameter: one parameter has one value, and one parameter has multiple values!> ***** String getParameter (String name): obtains the request parameter value of the specified name. It is applicable to single-value Request Parameters> String [] getParameterValues (String name ): obtain the request parameter value of the specified name. It is applicable to multivalue Request Parameters> Enumeration <String> getParameterNames (): obtain all request parameter names> ***** Map <String, string []> getParameterMap (): obtains all request parameters, where key is the parameter name and value is the parameter value. **/Public class EServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);} public void doPost (HttpServletRequest, request, httpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); // call it to solve the garbled problem. If not, you can refer to the String name = request I wrote to solve the garbled problem. getParameter ("name"); String password = request. getParameter ("password"); String [] aihao = request. getParameterValues ("aihao"); response. setHeader ("content-type", "text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); pw. println ("name:" + name + "<br/>"); pw. println ("password:" + password + "<br/>"); pw. print ("aihao"); for (int I = 0; I <aihao. length; I ++) {switch (I) {case 1: pw. print ("dinner"); break; case 2: pw. print ("sleeping"); break; case 3: pw. print ("doubebean"); break; default: break;} pw. close ();}}
<! -- Html used to send requests --> 

Application 4: Set request Object Attributes

It is used to realize the transfer between servlet of the same application. We also use forwarding.

/***** The request domain Servlet has three domain objects: request, session, and application:> void setAttribute (String name, Object value)> object getAttribute (String name)> void removeAttribute (String name);> use request within the same request range. setAttribute (), request. getAttribute () to pass the value! The previous Servlet calls setAttribute () to save the value, and the other Servlet calls getAttribute () to obtain the value. **/Public class FServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setAttribute ("name", "weijinhao"); request. setAttribute ("password", "123"); RequestDispatcher rd = request. getRequestDispatcher ("/GServlet"); rd. forward (request, response );}}
public class GServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)       throws ServletException, IOException {     String name = (String)request.getAttribute("name");     String password = (String)request.getAttribute("password");     response.setHeader("content-type", "text/html;charset=utf-8");     PrintWriter pw = response.getWriter();     pw.println("name:" + name + "<br/>");     pw.println("password:" + password + "<br/>");     pw.close();   }  } 

Well, the usage of the request is generally too much.

Let's take a look at the response object.

Use of response object

The http Protocol defines the format of the response browser.:

Response line
Response Header
Space
Response body

The general application of the response object is to set the response code, set the response header, and set the response body.

Application 1 sets the response body

/*** Response body ** 1, response stream * 2, byte stream */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// String n = "hello javaweb"; // byte [] B = n. getBytes (); // use of byte streams/* ServletOutputStream outputStream = response. getOutputStream (); outputStream. write (B); outputStream. close (); * // use the callback stream/* PrintWriter p = response. getWriter (); p. write (n); p. close (); * // use FileInputStream fileInputStream = new FileInputStream for commoms Toolkit ("C:/Users/74087/Desktop/6226354_994604.jpg"); byte [] B = IOUtils. toByteArray (fileInputStream); ServletOutputStream outputStream = response. getOutputStream (); outputStream. write (B); outputStream. close ();}}

Application 2: Set the response code and Response Header

/*** Response code * 1, sendError (int SC) // send error code * 2, sendError (int SC, java. lang. string msg) // send error code and Description * 3, setStatus (int SC) // send success response code * response Header of response * 1, setDateHeader (java. lang. string name, long date) * 2, setHeader (java. lang. string name, java. lang. string value) * 3, setIntHeader (java. lang. string name, int value) * The following functions the same as above, but is used to add * addDateHeader (java. lang. string name, long date) * addHeader (java. lang. string name, java. lang. string value) * addIntHeader (java. lang. string name, int value) */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// sendNum (response); // sensid (response ); // refresh (response); // noCache (response);} // disable the public void noCache (HttpServletResponse response) {response. setHeader ("Cache-Control", "no-cache"); response. setHeader ("pragma", "0"); response. setHeader ("expires", "no-cache");} // automatically jump to public void refresh (HttpServletResponse response) {response. setHeader ("refresh", "5; url = http://www.baidu.com ");} // Use public void sendh (HttpServletResponse response) {response. setStatus (302); response. setHeader (" Location "," http://www.baidu.com ");} Public void sendNum (HttpServletResponse response) throws IOException {response. setStatus (200); response. sendError (404); response. sendError (404, "ser accept your request but I don't want to you see my web page ");}}

If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.