[SpringMVC] Request-Corresponding to obtain request parameters + solution to related problems

2. Request


 

1.1 4 types of request parameters

The format of the request parameter of the customer service side is:...?username=Alice&age=12...

When the SpringMVC framework receives request parameters, it can also encapsulate them: ①Basic type ②POJO type ③array type ④collection type

 

1.2 Obtaining request parameters-basic types

Automatic matching based on name. And can automatically type conversion (String -> ?)

@RequestMapping("/test1")
@ResponseBody
public void test10(String username, int age) throws IOException {
    
    
    System.out.println(username);
    System.out.println(age);
    // http://localhost:8080/test1?username=Alice&age=12
}

 

1.3 Obtaining request parameters-POJO type

It can also be automatically matched based on the name!

@RequestMapping("/test2")
@ResponseBody
public void test11(User user) throws IOException {
    
    
    System.out.println(user);
    // http://localhost:8080/test2?username=Alice&age=12
}

 

1.5 Get request parameters-array type

Still automatic matching.

@RequestMapping("/test3")
@ResponseBody
public void test3(String[] lolis) throws IOException {
    
    
    System.out.println(Arrays.toString(arr));
    // http://localhost:8080/test3?lolis=Alice&lolis=Cocoa&lolis=Hana
}

 

1.6 Get request parameters-collection type

Note that you cannot automatically match the request parameter name directly here, but you must use the POJO type to transition.

Difficulty! ! ! Figure out how to transition and correspond ! ! !

domain.VO过渡类 ----------------------------------------------------------------------------

public class VO {
    
    

    private List<User> userList;

    // generate...
}
<!-- form.jsp页面 -- 简单的get方式不好模拟请求参数,因此使用表格post方式模拟请求参数 -->
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/test4" method="post">
        <input type="text" name="userList[0].username" />
        <input type="text" name="userList[0].age" />
        <br />
        <input type="text" name="userList[1].username" />
        <input type="text" name="userList[1].age" />
        <br />
        <input type="text" name="userList[2].username" />
        <input type="text" name="userList[2].age" />
        <br />
        <input type="submit" value="提交">
    </form>
</body>
</html>
@RequestMapping("/test4")
@ResponseBody
public void test4(VO vo) throws IOException {
    
    
    System.out.println(vo);
    // http://localhost:8080/form.jsp
}

 

1.7 Get request parameters-collection type (special case: Ajax json request parameters)

When the request is sent by Ajax and the contentType is in json format, it can be directly obtained with the collection type annotated with @RequestBody .

<!-- ajax.jsp页面 -->
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js" />
    <script>
        var userList = new Array();
        userList.push({
     
     username:"Alice",age:12});
        userList.push({
     
     username:"Hana",age:10});
        $.ajax({
     
     
            type:"POST",
            url:"${pageContext.request.contextPath}/test5",
            data:JSON.stringify(userList),
            contentType:"application/json;charset=utf-8"
        });
    </script>
</head>
<body>

</body>
</html>
@RequestMapping("/test5")
@ResponseBody
public void test5(@RequestBody List<User> userList) throws IOException {
    
    
    System.out.println(userList);
    // http://localhost:8080/ajax.jsp
}

 
 
 
 

2.1 The problem of not being able to find resources-enabling static resource access

When we visit such as /js/jquery-3.3.1.jsor in the SpringMVC framework /img/pic1.jpg, it shows that the directory or resource cannot be found .

This is because when we configured the core of the entire framework-the front controller DispatcherServlet, we wrote this:

<servlet>
     <servlet-name>DispatcherServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	 <!-- ... -->
</servlet>
<servlet-mapping>
     <servlet-name>DispatcherServlet</servlet-name>
     <url-pattern>/</url-pattern>
</servlet-mapping>

Note <url-pattern>/</url-pattern>the meaning of this sentence : all resources (dynamic resources/static resources) will be intercepted by DispatcherServlet.

Therefore, what we have to do is to "release" these static resources. In other words, open their access rights.

In spring-mvc.xml, there are the following two configuration methods:

<!-- 1.开放静态资源的访问权限 -->
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/img/**" location="/img/" />

<!-- 2.访问静态资源的工作交给Tomcat -->
<mvc:default-servlet-handler />

 
 

2.2 Chinese data garbled problem-global utf-8 filter

The Chinese request data in POST mode will cause garbled characters. We use a global filter to solve it.

<!-- 配置全局过滤器,解决中文乱码问题 -->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 
 

2.5 Inconsistent parameter names-binding annotation @RequestParam

The requested parameter name may be inconsistent with the received parameter name. At this time, you need to bind these two different names with the help of @RequestParam annotation.

@RequestMapping("/test6")
@ResponseBody
public void test6(@RequestParam("name") String username) throws IOException {
    
    
    System.out.println(username);
    // http://localhost:8080/test6?name=Alice
}

This annotation is very powerful:

-------------------------------------------------------------------------------------------
注解@RequestParam还可以配置的参数:
	- value: 请求参数的名称
	- required: 请求是否必须包含该参数(默认true)
	- defaultValue: 当请求不包含该参数时,则使用的默认值

-------------------------------------------------------------------------------------------

@RequestMapping("/test7")
    @ResponseBody
    public void test7(@RequestParam(value = "name", required = false, defaultValue = "Alice") String username) throws IOException {
    
    
        System.out.println(username);
        // http://localhost:8080/test7
    }

 
 

2.3 The URL address is the parameter problem-placeholder annotation @PathVariable

Restful style requests use "URL + request method (GET/POST/PUT/DELETE)" to indicate a purpose.

And, the request parameter no longer ?key=valuefollows the URL tail in the format of, but as a part of the URL address (for example http://localhost:8080/test/Alice).

Therefore, when obtaining the request parameters, placeholders and @PathVariable annotations are needed .

@RequestMapping("/test8/{username}")
@ResponseBody
public void test8(@PathVariable("username") String username) throws IOException {
    
    
    System.out.println(username);
    // http://localhost:8080/test8/Alice
}

 
 

2.4 Date format problem-custom type conversion factory

SpringMVC provides a default type converter when we use to intbe received String.

However, the date format differs greatly from country to country. SpringMVC can convert yyyy/MM/dda string into a date type, but yyyy-MM-ddit can't do anything with such a string.

We can write a type converter that inherits the Converter<S,T> interface by hand and add it to the type conversion factory.

① Custom type converter (converter.DateConverter.class)

public class DateConverter implements Converter<String, Date> {
    
    

    // 实现接口内部的convert方法
    public Date convert(String s) {
    
    
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
    
    
            date = format.parse(s);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return date;
    }
}

② Make relevant declarations in the configuration file (spring-mvc.xml)

<!-- 将自定义的转换器加到转换器工厂当中 -->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.samarua.converter.DateConverter" />
        </list>
    </property>
</bean>

<!-- 在配置注解驱动时声明转换器工厂 -->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean" />

③ Test

@RequestMapping("/test9")
@ResponseBody
public void test9(Date date) throws IOException {
    
    
    System.out.println(date);
    // http://localhost:8080/test9?data=2022-12-12
}

 
 

2.5 Native API issues-written in the method parameters for automatic injection

This problem has been mentioned before: In the SpringMVC framework environment, if you want to use the WebServlet native API, you can write these native objects in the method parameters, and the caller (ie the framework) will automatically inject it, so we can use it with confidence.

@RequestMapping("/test10")
@ResponseBody
public void test10(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
    
    
    System.out.println(request);
    System.out.println(response);
    System.out.println(session);
}

 
 
 
 

3. Get the request header

All the content above is to get the information of the request line . Next, we try to get the information of the request header .

First of all, it is clear that the format of the request line is [request method request url request protocol/version], and the format of the request header is [key-value pair] (see the figure below)

Insert picture description here

To obtain the information of any key-value pair in the request header, use the @RequestHeader annotation:

@RequestMapping("/test11")
@ResponseBody
public void test11(@RequestHeader(value = "User-Agent") String userAgent) throws IOException {
    
    
    System.out.println(userAgent);
}

In special cases, directly obtain the information of any key-value pair in the Cookie in the request header, and use the @CookieValue annotation:

@RequestMapping("/test12")
@ResponseBody
public void test12(@CookieValue(value = "JSESSIONID") String JSESSIONID) throws IOException {
    
    
    System.out.println(JSESSIONID);
}

 
 
 
 

 
 
 
 

 
 
 
 

More >_<

Guess you like

Origin blog.csdn.net/m0_46202073/article/details/114321204