接收请求参数及数据回显
SpringMVC接收前端数据不再需要使用Request,可以直接获取
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/t1")
public String test1(String name, Model model){
//1.接收前端参数
System.out.println("接收到前端的参数为:"+name);
//2.将结果从传递给前端
model.addAttribute("msg",name);
//3.跳转视图
return "test";
}
}
http://localhost:8080/user/t1?name=无双
控制台输出 接收到前端的参数为:无双
前端接收到:无双
若前后端字段不匹配则需要使用@RequestParam与前端字段保持一致
前端接收对象
直接传入对象
@RequestMapping("/t2")
public String test2(User user){
System.out.println(user);
return "test";
}
控制台输出:
User(id=1, name=无双, age=18)
使用对象字段名和前端名字必须一直,不然会返回null
乱码问题
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/e/t1" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
@Controller
public class EncodingController {
@PostMapping("/e/t1")
public String test1(String name, Model model){
model.addAttribute("msg",name);
return "test";
}
}
显示页面:
在控制台接收输出
???
发现后端接收的时候已经乱码
添加request.setCharacterEncoding(“utf-8”);
测试
俺是个
依旧乱码
添加过滤器
1.传统方式,手写
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.liu.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.使用SpringMVC自带的乱码过滤器
<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>