springmvc中提供CharacterEncodingFilter,处理post乱码
在web.xml配置过滤器
<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> 复制代码
如果是get方式乱码
a)修改tomcat的配置解决
b)自定义乱码解决的过滤器
优点:轻量级,安全,效率高
@RequestMapping("/hello/{name}")
public String hello(@PathVariable String name) {
System.out.println(name);
return "index.jsp";
}
复制代码
当我们输入 http://localhost:8080/02springweb_annotation/hello/1.do
的时候,控制台就会输出 1
。
我们也可以将参数放在hello前面,也可以拥有多个参数。
@RequestMapping("/{name}/{id}/hello")
public String hello(@PathVariable String name,@PathVariable int id) {
System.out.println(name);
System.out.println(id);
return "index.jsp";
}
复制代码
输入 http://localhost:8080/02springweb_annotation/asd/10/hello.do
,就可以在控制台看到结果了。
@Controller
@RequestMapping("/hello2")
public class ControllerMethod {
@RequestMapping(params="method=add")
public String add() {
System.out.println("add");
return "redirect:/index.jsp";
}
@RequestMapping(params="method=delete")
public String delete() {
System.out.println("delete");
return "redirect:/index.jsp";
}
}
复制代码
输入 http://localhost:8080/02springweb_annotation/hello2.do?method=add
,控制台就会输出 add
,代表add方法执行了。