The difference between the Request Response Comments

Author: Dream-Li
Source: CSDN
Original: https://blog.csdn.net/DreamLi1314/article/details/78906783
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Request

1, the basic information acquisition request
2, url and acquisition request URI
. 3, part of the string parameter acquisition request url behind
4 acquisition request mode
5, acquires the host name, IP address
6, obtaining Contexpath

String url = request.getRequestURL().toString();
System.out.println(url);

String uri = request.getRequestURI().toString();
System.out.println(uri);

String params = request.getQueryString();
System.out.println(params);

String method = request.getMethod();
System.out.println(method);

String addr = request.getRemoteHost() + request.getRemotePort() + request.getRemoteAddr() +
“==user=” + request.getRemoteUser();
System.out.println("addr: " + addr);

String contextPath = request.getContextPath();
response.sendRedirect(contextPath + “/index.jsp”);

1. Referer request header to achieveHotlink Protection

Referer request header indicates access link on the page from which the link to the current
hotlinking: other sites via hyperlinks link to your site in order to achieve resource theft hotlinking called
the @WebServlet ( "/ NewsServlet")
public class the extends the HttpServlet {NewsServlet
Private Long static Final serialVersionUID = 1L;
protected void the doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
the response.setContentType ( "text / HTML; charset = UTF-. 8");

   String referer = request.getHeader("Referer");
   if(referer == null || "".equals(referer) || !referer.contains("localhost/")) {
       response.sendRedirect(request.getContextPath() + "/index.jsp");
   }
   
   response.getWriter().write("习大大吃包子....");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   doGet(request, response);
}

}

If Referer is null or is not coming from your own site access will be redirected to your site's home page.

2. Get the request parameters

Map<String, String[]> params = request.getParameterMap();
for (String name : params.keySet()) {
String value = request.getParameter(name);
System.out.println(“name=” + name + “, value=” + value);
}

Request solve the garbage problem:

request.setCharacterEncoding ( "Utf-8") ;
If the above POST code can solve the problem of distortion, it can be decoded on their own
String request.getParameter the userName = ( "username");
the userName = new new String (userName.getBytes ( "ISO8859-1"), "UTF- 8");

Anterior using UTF-8 encoding, transmitting to the server, the server can use ISO8859-1 decoded code value of the UTF-8 encoded and then decoded by new String (bytes, charset) manner.

Set and get Domain Properties

Object attr = request.getAttribute(“attr”);

request.setAttribute(“key”, “value”);

request.removeAttribute(“attr”);

Enumeration attributeNames = request.getAttributeNames();

Our application is a servlet general data processing, the processed data into the request field, and then taken for display on-jsp page.

Forwarding the request comprises a request
forwards the request:
. Request.getRequestDispatcher ( "/ DispatcherTest2") Forward (Request, Response);
or
this.getServletContext () getRequestDispatcher ( "/ DispatcherTest2 ") forward (request, response);..

Note:
1) a request to forward only once, otherwise the following exception occurs: - data can be forwarded first acquired
java.lang.IllegalStateException: the After the Response of Can not Forward has been committed
2) When the data has been written to the client and then forwards the request will throw an exception end.

3)若转发前有数据写入到response缓冲区,则请求转发会清空response缓冲区的实体内容, 但不会清空请求头信息.

The request contains:

When it is desired to merge the output of the plurality of servlet may be used when a call request contains the browser
request.getRequestDispatcher ( "/ DispatcherTest2") include (request, response);.
Or
. This.getServletContext () getRequestDispatcher ( "/ DispatcherTest2" ) .include (request, response);

Notice:
. 1) contained in the program is the Servlet can not change the status code and the response header of the response message, if there is a statement in it, the results of these statements are ignored.
2) is often used for page layout

Redirect requests:

response.sendRedirect(request.getContextPath() + “/DispatcherTest2”);

Notice:

  1. Then redirects the request after the data has not sent to the browser:
    a java.lang.IllegalStateException: Can the sendRedirect Not Call () After The Response has been committed

  2. Response data is written to the buffer prior to the redirection request will be cleared

  3. A request can only be redirected once

Summary:
Redirect requests the address bar will change request forwarding address bar does not change.
Redirects the request to forward the request in response to two requests twice a response to a request.

If you need to use the domain property domain transfer request when the resource request is forwarded to jump you must use
to modify user's resources after the jump if you want to use the address bar to redirect requests

If you use request forwarding can also redirect can be inserted, then the request is forwarded to reduce the number of browser access to the server to reduce the pressure on the server.

Response

1.response

ServletResponse -- 通用的response提供了一个响应应该具有最基本的属性和方法
    |
    |-HttpServletResponse -- 在ServletResponse的基础上针对于HTTP协议增加了很多强化的属性和方法

2. Output Data

1) getOutputStream output stream of bytes
response.getOutputStream () write ( "China" .getBytes ( "utf-8" .));

string.getBytes () if the encoding is not specified, it will use the platform default encoding

2) getWriter character output stream

. response.getWriter () write ( "Beijing");
Notice: the getWriter getOutputStream and can only be used in a single request
using Chinese character output stream, since only the output network line high and low, if no encoding, when transmitting data the server uses the default ISO-8859-1 encoded data (the code table no characters, characters will be encoded so as?, the data transferred to the browser actually is?).

3) to solve the garbage

1> 通知服务器发送数据时使用utf-8编码

response.setCharacterEncoding(“utf-8”);

2> 通知浏览器接受数据时使用utf-8解码

response.setHeader(“Content-Type”, “text/html;charset=utf-8”);

3> Notice:
    a. response对象中对Content-Type响应头进行了封装,可以使用一下代码代替 2>

the response.setContentType ( "text / HTML; charset = UTF-. 8");
. If the Content-Type B, the server automatically setting characterEncoding provided, so only need to solve the garbage disposed Content-Type header in response to the line of code, but in order to more readable code, while generally it is recommended to set characterEncoding and Content-Type.

3) Implementation

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader(“Content-Disposition”, “attachment;filename=” + URLEncoder.encode(“美女.jpg”));
InputStream in = new FileInputStream(this.getServletContext().getRealPath(“美女.jpg”));
OutputStream out = response.getOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while(-1 != (len = in.read(bytes))) {
out.write(bytes, 0, len);
}
in.close();
}

4) realizationRegularly updated(Registration is successful, return home after three seconds)

1.Servlet实现

response.setContentType ( "text / HTML; charset = UTF-8");
. response.getWriter () the Write ( "Congratulations on your successful registration, 3 seconds back to the home page");
response.setHeader ( "Refresh", "3 ; url = OutServlet ");

2.html实现
Insert title here Congratulations on your successful registration, 3 seconds back home ....

5) control whether the browser cache

response.setIntHeader(“Expires”, -1);
response.setHeader(“Cache-Control”, “no-cache”);
response.setHeader(“Pragma”, “no-cache”);
response.getWriter().write(new Date().toLocaleString());

6) fulfill the request redirection

response.sendRedirect(this.getServletContext().getContextPath());

Author: Dream-Li
Source: CSDN
Original: https://blog.csdn.net/DreamLi1314/article/details/78906783
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin blog.csdn.net/qq_39263750/article/details/90213614