# 亂碼問題解決 ###### tags: `SpringMVC-基礎` #### 1.先創建一個可以提交的jsp頁面的表單 ```xml= <html> <head> <title>Title</title> </head> <body> <form action="/e/t1" method="post"> <input type="text" name="name"> <input type="submit"> </form> </body> </html> ``` #### 2.後台編寫的對應類 ```java= @Controller public class EncodingController { @PostMapping("/e/t1") public String test1(String name, Model model){ model.addAttribute("msg",name); return "test"; } } ``` #### 3.記得也要再web.xml中註冊這個jsp頁面(有可以跳過這步的方法嗎?) ```xm= <servlet> <servlet-name>form</servlet-name> <jsp-file>/WEB-INF/jsp/form.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>form</servlet-name> <url-pattern>/form</url-pattern> </servlet-mapping> ``` #### 4.訪問到form表單中  #### 5.測試 數字:成功  中文:亂碼   ### 解決方式1:使用過濾器來解決亂碼 #### 1.創建過濾器(filter) ```java= public class EncodignFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } } ``` #### 2.在web.xml配置過濾器 ```xml= <filter> <filter-name>encoding</filter-name> <filter-class>com.kuang.filter.EncodignFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/</url-pattern> </filter-mapping> ``` #### 3.再次測試  ### 失敗  ### 解決方式二:修改請求方式 #### 1.將頁面的請求改成GET ```xml= <html> <head> <title>Title</title> </head> <body> <form action="/e/t1" method="get"> <input type="text" name="name"> <input type="submit"> </form> </body> </html> ``` #### 2.處理的對應類也要修改請求方式,改成@GetMapping ```java= @Controller public class EncodingController { //過濾器解決亂碼 @GetMapping ("/e/t1") public String test1(String name, Model model){ model.addAttribute("msg",name); return "test"; } } ``` #### 3.測試  ### 成功  ## SpringMVC解決亂碼的方式 SpringMVC提供一個過濾器,可以在web.xml中配置,修改xml文件需要重啟服務器 ```xml= <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> ``` #### 測試  ### 成功 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up