Servlet request garbled problem, request forwarding problem

Receiving Chinese garbled characters

problem

When the LoginServlet receives a client request, the Chinese in the form data is garbled

for example:

  • Account Number: Zhang San
  • Password; 123

Get request data:

  • account number:? ?
  • Password: 123

solve

1. Use String to re-encode data

Core data try to use this method

Both get and post are valid in this way

After obtaining the account, manually convert the encoding format to UTF-8

String uname = req.getParameter("uname");
uname = new String(uname.getBytes("iso8859-1"),"UTF-8");

A tool class can be encapsulated when used

/**
 * 对字符集进行正确的编码,防止乱码出现
 * @return
 */
public static String encoding(String value,String charset) {
    
    
    try {
    
    
        if (value != null) {
    
    
            value = new String(value.getBytes("iso8859-1"),charset);
        }
    } catch (UnsupportedEncodingException e) {
    
    
        e.printStackTrace();
    }
    return value;
}

2. Use public configuration

Public configuration, all requests will change the encoding format

resp.setContentType("text/html;charset=utf-8");

  • get method

    • Set the request encoding format:req.setCharacterEncoding("utf-8");
    • Modify the server.xml file in the conf directory under the Tomcat directory:
      • Add attributes to the Connector tag:useBodyEncodingForURI="true"
  • post method

    • Before obtaining the request, set the request encoding format

      req.setCharacterEncoding("utf-8");


Servlet process summary

  • Servlet use process
    • Set the request encoding format
    • Set response encoding format
    • Get request information
    • Processing request information
    • Response processing result
  • Data flow process
    • Browser-server-database
    • Database-Server-Browser

Request forwarding

problem

After the login fails, the login failed is displayed, and you should jump back to the login page. If in the servlet that handles the login, writing the page will cause code redundancy and unclear responsibilities

solve

Use request forwarding

  • Features
    • The address bar information does not change

req.getRequestDispatcher().forward()

Request forwarding cannot form a circular chain, and a 500 error will be reported

  • Role: Realize multiple servlet linkage operations to process requests, so as to avoid code redundancy and make the servlet's responsibilities more clear

  • use:

    req.getRequestDispatcher("/要跳转地址的别名").forward(req,resp);

    • /: Represents the project root directory

    • Address: relative path, just write the alias of the servlet directly

      It is recommended to use absolute path (/resource path) for development

Features

  • Request together, the browser address bar information does not change.
    • Login address bar: http://localhost:8080/login——After login:http://localhost:8080/loginyz
    • Login failed. After forwarding the page, the address bar:, http://localhost:8080/loginyzbut the Login page is displayed

note:

  • After the request is forwarded, just return directly to the end.

The scope of the request object

After using request forwarding, how to share data between different Servlets? Or how does data flow from one Servlet to another Servlet?

  • Solution: Use the scope of the request object

  • 使用:req.setAttribute(Object name,Object value);

​ req.getAttribute(Object obj);

  • Role: Solved the data sharing problem of different Servlets in a request

  • Scope: Based on request forwarding, all Servlets in a request are shared

  • Note: Use the Request object for data flow, and the data is only valid within one request

  • Features:

    • Server creation
    • Every request will be created
    • Life cycle: one request

use

  • req.setAttribute("str","账号或密码错误");

Page processing Servlet to get prompt information

  • String option = (String) req.getAttribute("str");

  • method one:

    String option = (String) req.getAttribute("str");
    if(option!=null){
          
          
    	resp.getWriter().write("<b>"+option+"</b>");
    }
    
  • Way two:

    String option = (String) req.getAttribute("str") == null?"":(String) req.getAttribute("str");
    resp.getWriter().write("<font color='red' size='20px'>"+option+"</font>");
            
    

Data echo

<td>
    <% String name = request.getParameter("username");%>
    <input type="text" name="username" value="<%=name==null?"":name%>" />
</td>

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/114058144