[SSM hits the big factory directly] Chapter 6: SpringMVC gets request data

content

SpringMVC gets request data

1. Get request parameters

2. Request garbled characters

3. Parameter binding annotation @RequestParam

4. Get Restful-style parameters

5. Custom Type Converters

6. Get the request header

7. File upload

8. Summary


c8a1e35319f448739dd23d6d8ce31930.png6ee7f9c8dfb4455d910622806668da71.png​​​​​​​

SpringMVC gets request data

1. Get request parameters

The format of the client's request parameters is: name=value&name=value... ... The server needs to obtain the requested parameters, and sometimes data encapsulation is required. SpringMVC can receive the following types of parameters:

1) Basic type parameters:​​​​​​​
 
The parameter name of the business method in the Controller must be the same as the name of the request parameter, and the parameter value will be automatically mapped and matched.
//http://localhost:8080/project/quick9?username=zhangsan&age=12
@RequestMapping("/quick9")
@ResponseBody
public void quickMethod9(String username,int age) throws IOException {
    System.out.println(username);
    System.out.println(age);
}
2) POJO type parameters:
 
The attribute name of the POJO parameter of the business method in the Controller is the same as the name of the request parameter, and the parameter value will be automatically mapped and matched.
//http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12
public class User {
    private String username;
    private int age;
    getter/setter…
}
@RequestMapping("/quick10")
@ResponseBody
public void quickMethod10(User user) throws IOException {
    System.out.println(user);
}
3) Array type parameters
 
The name of the business method array in the Controller is the same as the name of the request parameter, and the parameter value will be automatically mapped and matched.
//http://localhost:8080/project/quick11?strs=111&strs=222&strs=333
@RequestMapping("/quick11")
@ResponseBody
public void quickMethod11(String[] strs) throws IOException {
    System.out.println(Arrays.asList(strs));
}
4) Collection type parameters
 
When getting a collection parameter, you need to wrap the collection parameter into a POJO.
<form action="${pageContext.request.contextPath}/quick12" method="post">
 <input type="text" name="userList[0].username"><br>
 <input type="text" name="userList[0].age"><br>
 <input type="text" name="userList[1].username"><br>
 <input type="text" name="userList[1].age"><br>
 <input type="submit" value="提交"><br>
</form>
@RequestMapping("/quick12")
@ResponseBody
public void quickMethod12(Vo vo) throws IOException {
    System.out.println(vo.getUserList());
}
      When using ajax to submit, you can specify the contentType as json , then use @RequestBody in the method parameter position to receive collection data directly without wrapping it with POJO.
​​​​​​​
<script>
//模拟数据
var userList = new Array();
userList.push({username: "zhangsan",age: "20"});
userList.push({username: "lisi",age: "20"});
$.ajax({
type: "POST",
url: "/itheima_springmvc1/quick13",
data: JSON.stringify(userList),
contentType : 'application/json;charset=utf-8'
});
</script>
@RequestMapping("/quick13")
@ResponseBody
public void quickMethod13(@RequestBody List<User> userList) throws 
IOException {
    System.out.println(userList);
}
Notice:
Through the Google developer tools to capture the package, it is found that the jquery file is not loaded, the reason is the front controller of SpringMVC
The url-pattern of DispatcherServlet is configured with /, which means that all resources are filtered. We can specify the release of static resources in the following two ways:
• Specify the released resources in the spring-mvc.xml configuration file
<mvc:resources mapping="/js/**" location="/js/"/>
• Or use the <mvc:default-servlet-handler/> tag
 

2. Request garbled characters

When the post request, the data will appear garbled, we can set a filter in web.xml to filter the encoding.

<!--资源过滤器-->
    <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>
When the parameter name of the request is inconsistent with the parameter name of the controller's business method, the binding displayed by the @RequestParam annotation is required.
<form action="${pageContext.request.contextPath}/quick14" method="post">
 <input type="text" name="name"><br>
 <input type="submit" value="提交"><br>
</form>

3. Parameter binding annotation @RequestParam

The annotation @RequestParam also has the following parameters that can be used:
value request parameter name
required Whether the specified request parameters must be included, the default is true, if there is no such parameter when submitting, an error will be reported
defaultValue When no request parameter is specified, the specified default value is used for the assignment
​​​​​​​
@RequestMapping("/quick14")
@ResponseBody
public void quickMethod14(@RequestParam(value="name",required = 
false,defaultValue = "defaultname") String username) throws IOException {
System.out.println(username);
}

4. Get Restful-style parameters

 

Restful is a software architectural style and design style , not a standard, but only provides a set of design principles and constraints. Mainly used for client-server interaction software, software designed based on this style can be more concise, more hierarchical, and easier to implement caching mechanisms.
 
Restful -style requests use "url + request method" to indicate the purpose of a request. The four verbs in the HTTP protocol that indicate the operation method are as follows:
GET : Access to resources
DELETE: delete resource
PUT: Update resources
POST:
New resource ​​​​​​​​​​​​​​
E.g:
/user/1 GET : get user with id = 1
/user/1 DELETE: delete user with id = 1
/user/1 PUT: update user with id = 1
user POST:
Add user​​​​​​​​​​​​​​
 
The 1 in the above url address /user/1 is the request parameter to be obtained, and placeholders can be used for parameter binding in SpringMVC. The address /user/1 can be written as /user/{id}, and the placeholder {id} corresponds to the value of 1. In the business method, we can use the @PathVariable annotation to match placeholders.
//http://localhost:8080/itheima_springmvc1/quick19/zhangsan
@RequestMapping("/quick19/{name}")
@ResponseBody
public void quickMethod19(@PathVariable(value = "name",required = true) String name){
System.out.println(name);
}

5. Custom Type Converters

 

• Although SpringMVC has provided some common type converters by default, for example, the string submitted by the client is converted into an int type for parameter setting.
• But not all data types provide converters, and custom converters are required for those not provided, for example, date data types require custom converters.
Development steps for custom type converters:
① Define the converter class to implement the Converter interface
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
② Declare the converter in the spring-mvc.xml configuration file
<!--配置自定义转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="converter.DateConverter"/>
            </list>
        </property>
    </bean>
③ Refer to the converter in <annotation-driven>
 <!--注解驱动-->
    <mvc:annotation-driven conversion-service="conversionService"/>

6. Get the request header

@RequestHeader

Use @RequestHeader to get request header information, which is equivalent to request.getHeader(name) learned in the web stage
The properties of the @RequestHeader annotation are as follows:
value
the name of the request header
required Whether to carry this request header
 
@RequestMapping("/quick17")
@ResponseBody
public void quickMethod17(@RequestHeader(value = "User-Agent",required = false) String 
headerValue){
    System.out.println(headerValue);
}
@CookieValue
 
Use @CookieValue to get the value of the specified cookie
The attributes of the @CookieValue annotation are as follows:
value
Specify the name of the cookie
required Is it mandatory to carry this cookie
@RequestMapping("/quick18")
@ResponseBody
public void quickMethod18(@CookieValue(value = "JSESSIONID",required = false) String jsessionid){
    System.out.println(jsessionid);
}

7. File upload

Three elements of the file upload client:

  1. Form item type="file"
  2. The form is submitted by post
  3. The enctype attribute of the form is a multipart form form, and enctype="multipart/form-data"​​​​​​​​​​​​​​
<form action="${pageContext.request.contextPath}/quick20" method="post" 
enctype="multipart/form-data">
名称:<input type="text" name="name"><br>
文件:<input type="file" name="file"><br>
 <input type="submit" value="提交"><br>
</form>

 File upload steps

Import fileupload and io coordinates in pom.xml

<!--文件下载-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>

② Configuration file upload parser

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="500000"/>
    </bean>
③ Write file upload code
@RequestMapping("/quick8")
    @ResponseBody
    public void save8(String name, MultipartFile uploadfile) {
        System.out.println("save8 running...");
        System.out.println(name);
        String filename = uploadfile.getOriginalFilename();
        try {
            uploadfile.transferTo(new File("D:\\upload\\"+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

8. Summary

MVC implements data request parameter configuration
  • basic type parameter
  • POJO type parameters
  • array type parameter
  • Collection type parameters​​​​​​​
MVC get request data processing
  • Chinese garbled problem
  • @RequestParam 和 @PathVariable
  • Get Servlet related API
  • @RequestHeader 和 @CookieValue
  • File Upload

 

Guess you like

Origin blog.csdn.net/qq_52360069/article/details/123804314