数据处理
处理提交数据
-
当url传输的字段名一致时候
//http://localhost:8089/hello1?name=xiaohua @GetMapping("/hello1") public String hello1(String name){ System.out.println(name); return "hello"; }
-
当url传输的字段名不一致时候(使用@RequestParam绑定参数)
http://localhost:8089/hello2?username=xiaohua @GetMapping("/hello2") public String hello2(@RequestParam("username") String name){ System.out.println(name); return "hello"; }
-
当URL传入对象
//http://localhost:8089/hello3?name=xiaohua&age=21 @GetMapping("/hello3") public String hello3(User user){ System.out.println(user); return "hello"; }
@Component public class User { private String name; private Integer age; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
处理乱码
- SpringMVC给我们提供了一个过滤器 , 可以在web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置编码拦截器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
JSON
`
// 注意配置返回的编码类型,容易乱码
@GetMapping(value = "/hello4",produces = "application/json; charset=utf-8")
@ResponseBody
public String hello4(){
// 对象转JSON
User user = new User("小李",35);
return JSON.toJSONString(user);
}