1、乱码的解决
通过过滤器来解决乱码,Spring mvc 中提供CharacterEncodingFilter
乱码(post传递)问题:
http://localhost:8080/spring_data/user.do?name=艾伦
通过配置web.xml来解决:
在web.xml的servlet标签前面添加:
<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>*.do</url-pattern>
</filter-mapping>
完整:<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>02springmvc_hello</display-name>
<!-- spring mvc的配置 配置DispatcherServlet 这个类接管所有请求。 -->
<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>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定spring mvc配置文件的名称和位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
如果是get方式乱码:
a:修改Tomcat配置
b:自定义乱码解决的过滤器2、Restful风格的URL
优点:轻量级,效率高,安全
Hello2Controller.jsp(get提交)
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("hello2")
public class HelloController2 {
@RequestMapping(params = "method=add")
public String add() {
System.out.println("add()");
return "redirect:/add.jsp";
}
public String delete() {
System.out.println("delete()");
return "redirect:/delete.jsp";
}
public String update() {
System.out.println("update()");
return "redirect:/update.jsp";
}
public String search() {
System.out.println("search()");
return "redirect:/search.jsp";
}
}
浏览器运行:http://localhost:8080/spring_data/hello2.do?method=add
条转到:http://localhost:8080/spring_data/add.jsp
post提交:
@RequestMapping(params = "method=add",method=RequestMethod.POST)