New record learning and creation 1

1,@RequestMapping

Annotations used to handle request address mapping can be used on classes or methods. Used on a class to indicate that all methods in the class that respond to requests take this address as the parent path; It is used for methods. It means that adding the address in the annotation on the method under the parent path of the class will access the method. Here, it should be noted that @ RequestMapping can be used for classes, but it must be used for methods.

@Controller
@RequestMapping("device/")
public class DeviceController {
	@Autowired
	DeviceService deviceService;
 
	@RequestMapping("toDeviceImportPage")
	public String toDeviceImportPage() {
		return "page/deviceRecord/deviceImport";
	}
  1. @RequiresPermissions permission
@RequestMapping("/getRoleList")
	@RequiresPermissions("sys:role:list")
	@ResponseBody
	public ResultUtil getRoleList(Integer page,Integer limit) {
		return adminServiceImpl.selRoles(page, limit);
	}
  1. @What is the difference between Autowired and @ Resource?

Both can assemble bean s or write on setter methods.

@Autowired is assembled by type by default (this annotation belongs to industry spring). By default, dependent objects must exist. If null value is allowed, its required property can be set to false, such as @ Autowired(required=false). If we want to use name assembly, we can use it in combination with @ Qualifier annotation, as follows:

@Autowired() @Qualifier("baseDao")
 
private BaseDao baseDao;

@The default installation name of Resource (this annotation belongs to J2EE) is used for assembly. The name can be specified through the name attribute. If the name attribute is not specified, when the annotation is written on the field, the field name is used for installation name search by default. If the annotation is written on the setter method, the attribute name is used for assembly by default. Assemble by type when no bean matching the name is found. However, it should be noted that once the name attribute is specified, it will only be assembled by name.

@Resource(name="baseDao")
private BaseDao baseDao;
  1. @What is the difference between RequestParam and @ RequestBody?
    The parameters received by the RequestParam annotation come from the requestHeader, that is, the request header, that is, in the url. The format is xxx? username=123&password=456

The parameters received by the requestbody annotation come from the requestbody, that is, the request body.

If it is a get request, the annotation of the background received parameter should be RequestParam. If it is a post request, the annotation of the background received parameter is RequestBody.
get request

post request

5. The @ RestController annotation is equivalent to the combination of @ Controller+@ResponseBody annotations. It is not necessary to add the @ ResponseBody annotation in front of the method to return json data. However, if you use the @ RestController annotation, you cannot return JSP and HTML pages. The view parser cannot parse JSP and HTML pages

6. Introduction to HttpServletRequest:
The HttpServletRequest object represents the request of the client. When the client accesses the server through the HTTP protocol, all the information in the HTTP request header is encapsulated in this object. All the information requested by the client can be obtained through the methods provided by this object.
The getRequestURL method returns the full URL when the client makes a request.
The getRequestURI method returns the resource name part of the request line.

  String requestUrl = request.getRequestURL().toString();//Get the requested URL address
     String requestUri = request.getRequestURI();//Get requested resources

Get client request header

getHeader(string name)method:String
  getHeaders(String name)method:Enumeration
  getHeaderNames()method
  
  String headValue = request.getHeader(headName);//Get the value of the corresponding request header according to the name of the request header

Get client request parameters (data submitted by the client)
getParameter(String) method (common)
getParameterValues(String name) method (common)
getParameterMap() method (commonly used when writing framework)
/**

10

* Get client pass Form Parameters submitted by the form
11  */
12 public class RequestDemo03 extends HttpServlet {
13 
14     public void doGet(HttpServletRequest request, HttpServletResponse response)
15             throws ServletException, IOException {
16         //The client submits form data in UTF-8 code, so the server needs to be set to receive it in UTF-8 code, otherwise Chinese data will be garbled
17         request.setCharacterEncoding("UTF-8");
18         /**
19          * Edit & nbsp& nbsp; No. (text box):
20            <input type="text" name="userid" value="NO." size="2" maxlength="2">
21          */
22         String userid = request.getParameter("userid");//Get the number filled in. Userid is the name of the text box, < input type = "text" name = "userid" >
23         /**
24          * User name (text box): < input type = "text" name = "username" value = "please enter user name" >
25          */
26         String username = request.getParameter("username");//Get the user name filled in
27         /**
28          * Secret & nbsp& nbsp; Code (password box): < input type = "password" name = "userpass" value = "please enter password" >
29          */
30         String userpass = request.getParameter("userpass");//Get the password filled in
31         String sex = request.getParameter("sex");//Gets the selected gender
32         String dept = request.getParameter("dept");//Get the selected Department
33         //Obtain the selected interest. Because multiple values can be selected, the obtained value is a string array, so you need to use the getParameterValues method to obtain it
34         String[] insts = request.getParameterValues("inst");
35         String note = request.getParameter("note");//Get the description information filled in
36         String hiddenField = request.getParameter("hiddenField");//Gets the contents of the hidden field
37         
38         String instStr="";
39         /**
40          * The technique of obtaining array data can avoid the null pointer exception error caused when insts array is null!
41          */
42         for (int i = 0; insts!=null && i < insts.length; i++) {
43             if (i == insts.length-1) {
44                 instStr+=insts[i];
45             }else {
46                 instStr+=insts[i]+",";
47             }
48         }
49         
50         String htmlStr = "<table>" +
51                             "<tr><td>Filled in No.:</td><td>{0}</td></tr>" +
52                             "<tr><td>User name filled in:</td><td>{1}</td></tr>" +
53                             "<tr><td>Password filled in:</td><td>{2}</td></tr>" +
54                             "<tr><td>Selected gender:</td><td>{3}</td></tr>" +
55                             "<tr><td>Selected Department:</td><td>{4}</td></tr>" +
56                             "<tr><td>Selected interests:</td><td>{5}</td></tr>" +
57                             "<tr><td>Instructions for filling in:</td><td>{6}</td></tr>" +
58                             "<tr><td>Hide the contents of the field:</td><td>{7}</td></tr>" +
59                         "</table>";
60         htmlStr = MessageFormat.format(htmlStr, userid,username,userpass,sex,dept,instStr,note,hiddenField);
61         
62         response.setCharacterEncoding("UTF-8");//Set the server to output data to the client in UTF-8 encoding
63         response.setContentType("text/html;charset=UTF-8");//Set the client browser to parse data in UTF-8 encoding
64         response.getWriter().write(htmlStr);//Output the contents of htmlStr to the client browser for display
65     }
66 
67     public void doPost(HttpServletRequest request, HttpServletResponse response)
68             throws ServletException, IOException {
69         doGet(request, response);
70     }
71 }

On the server side, use the getParameterMap method to receive form parameters. The code is as follows:

           //The parameters encapsulated by the request object are stored in the form of Map
 2         Map<String, String[]> paramMap = request.getParameterMap();
 3         for(Map.Entry<String, String[]> entry :paramMap.entrySet()){
 4             String paramName = entry.getKey();
 5             String paramValue = "";
 6             String[] paramValueArr = entry.getValue();
 7             for (int i = 0; paramValueArr!=null && i < paramValueArr.length; i++) {
 8                 if (i == paramValueArr.length-1) {
 9                     paramValue+=paramValueArr[i];
10                 }else {
11                     paramValue+=paramValueArr[i]+",";
12                 }
13             }
14             System.out.println(MessageFormat.format("{0}={1}", paramName,paramValue));
15         }

Causes and solutions of garbled Chinese data submitted by POST
The client transmits data to the server in UTF-8 encoding, so it is necessary to set the server to receive in UTF-8 encoding, otherwise Chinese data will be garbled

request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");

Causes and solutions of garbled Chinese data submitted by GET
For data transmitted in get mode, even if the request is set to receive data in the specified code, it is invalid (I don't understand why it is invalid). By default, ISO8859-1 character code is used to receive data, and the client transmits data to the server in UTF-8 code, The request object on the server side uses the character code ISO8859-1 to receive data. The coding of communication between the server and the client is inconsistent, so Chinese garbled code will be generated. Solution: after receiving the data, first obtain the byte array of the original data received by the request object with ISO8859-1 character encoding, and then build a string with the specified encoding through the byte array to solve the problem of garbled code

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         *
         * For data transmitted in get mode, even if the request is set to receive data in the specified code, it is invalid. By default, ISO8859-1 character code is used to receive data
         */
        String name = request.getParameter("name");//receive data 
        name =new String(name.getBytes("ISO8859-1"), "UTF-8") ;//Get the byte array of the original data received by the request object with ISO8859-1 character encoding, and then build a string with the specified encoding through the byte array to solve the problem of garbled code
        System.out.println("name: "+name);
}

@What is the relationship between Param and @ RequestParam? In fact, they don't matter. Just like Java and JavaScript, Lei Feng and Lei Feng tower, they have a similar appearance, but their functions are different. @ Param is located in the Dao layer to pass multiple parameters and solve readability and intuition; The @ RequestParam is located in the Controller layer. It is used to obtain front-end parameters and solve the problem of inconsistent front-end and back-end parameters. So they don't matter!

Regular expression: eq(applet::getid) represents the getid attribute in the class applet (this attribute may also exist in other classes, all specifying a class)

Keywords: Java

Added by webJunk on Sun, 16 Jan 2022 05:56:32 +0200