SpringMVC入門學習---亂碼處理和Restful風格
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)自定義亂碼解決的過濾器
2.restful風格的url
優點:輕量級,安全,效率高
@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 intid) { System.out.println(name); System.out.println(id); return "index.jsp"; } 複製程式碼
輸入http://localhost:8080/02springweb_annotation/asd/10/hello.do
,就可以在控制檯看到結果了。
3.同一個controller通過引數來到達不同的處理方法--不重要
@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方法執行了。