Spring mvc如何實(shí)現(xiàn)數(shù)據(jù)處理
處理提交數(shù)據(jù)
1、提交的域名稱和處理方法的參數(shù)名一致
提交數(shù)據(jù) : http://localhost:8080/hello?name=xiaohua
處理方法 :
@RequestMapping('/hello')public String hello(String name){ System.out.println(name); return 'hello';}
后臺(tái)輸出 : xiaohua
2、提交的域名稱和處理方法的參數(shù)名不一致
提交數(shù)據(jù) : http://localhost:8080/hello?username=xiaohua
處理方法 :
//@RequestParam('username') : username提交的域的名稱 .@RequestMapping('/hello')public String hello(@RequestParam('username') String name){ System.out.println(name); return 'hello';}
后臺(tái)輸出 : xiaohua
3、提交的是一個(gè)對(duì)象
要求提交的表單域和對(duì)象的屬性名一致 , 參數(shù)使用對(duì)象即可
實(shí)體類
public class User { private int id; private String name; private int age; //構(gòu)造 //get/set //tostring()}
提交數(shù)據(jù) : http://localhost:8080/mvc04/user?name=xiaohua&id=1&age=15
處理方法 :
@RequestMapping('/user')public String user(User user){ System.out.println(user); return 'hello';}
后臺(tái)輸出 : User { id=1, name=’xiaohua’, age=15 }
說明:如果使用對(duì)象的話,前端傳遞的參數(shù)名和對(duì)象名必須一致,否則就是null。
數(shù)據(jù)顯示到前端
第一種 : 通過ModelAndView
我們前面一直都是如此 . 就不過多解釋
public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一個(gè)模型視圖對(duì)象 ModelAndView mv = new ModelAndView(); mv.addObject('msg','ControllerTest1'); mv.setViewName('test'); return mv; }}
第二種 : 通過ModelMap
ModelMap
@RequestMapping('/hello')public String hello(@RequestParam('username') String name, ModelMap model){ //封裝要顯示到視圖中的數(shù)據(jù) //相當(dāng)于req.setAttribute('name',name); model.addAttribute('name',name); System.out.println(name); return 'hello';}
第三種 : 通過Model
Model
@RequestMapping('/ct2/hello')public String hello(@RequestParam('username') String name, Model model){ //封裝要顯示到視圖中的數(shù)據(jù) //相當(dāng)于req.setAttribute('name',name); model.addAttribute('msg',name); System.out.println(name); return 'test';}
對(duì)比
Model 只有寥寥幾個(gè)方法只適合用于儲(chǔ)存數(shù)據(jù),簡(jiǎn)化了對(duì)于Model對(duì)象的操作和理解; ModelMap 繼承了 LinkedMap ,除了實(shí)現(xiàn)了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性; ModelAndView 可以在儲(chǔ)存數(shù)據(jù)的同時(shí),可以進(jìn)行設(shè)置返回的邏輯視圖,進(jìn)行控制展示層的跳轉(zhuǎn)。亂碼問題
SpringMVC給我們提供了一個(gè)過濾器 , 可以在web.xml中配置 .
修改了xml文件需要重啟服務(wù)器!
<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>
有些極端情況下.這個(gè)過濾器對(duì)get的支持不好 .
處理方法 :
修改tomcat配置文件 : 設(shè)置編碼!
<Connector URIEncoding='utf-8' port='8080' protocol='HTTP/1.1' connectionTimeout='20000' redirectPort='8443' />
自定義過濾器
package com.xiaohua.filter;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.Map;/** * 解決get和post請(qǐng)求 全部亂碼的過濾器 */public class GenericEncodingFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //處理response的字符編碼 HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType('text/html;charset=UTF-8'); // 轉(zhuǎn)型為與協(xié)議相關(guān)對(duì)象 HttpServletRequest httpServletRequest = (HttpServletRequest) request; // 對(duì)request包裝增強(qiáng) HttpServletRequest myrequest = new MyRequest(httpServletRequest); chain.doFilter(myrequest, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { }}//自定義request對(duì)象,HttpServletRequest的包裝類class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; //是否編碼的標(biāo)記 private boolean hasEncode; //定義一個(gè)可以傳入HttpServletRequest對(duì)象的構(gòu)造函數(shù),以便對(duì)其進(jìn)行裝飾 public MyRequest(HttpServletRequest request) { super(request);// super必須寫 this.request = request; } // 對(duì)需要增強(qiáng)方法 進(jìn)行覆蓋 @Override public Map getParameterMap() { // 先獲得請(qǐng)求方式 String method = request.getMethod(); if (method.equalsIgnoreCase('post')) { // post請(qǐng)求 try {// 處理post亂碼request.setCharacterEncoding('utf-8');return request.getParameterMap(); } catch (UnsupportedEncodingException e) {e.printStackTrace(); } } else if (method.equalsIgnoreCase('get')) { // get請(qǐng)求 Map<String, String[]> parameterMap = request.getParameterMap(); if (!hasEncode) { // 確保get手動(dòng)編碼邏輯只運(yùn)行一次for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null) { for (int i = 0; i < values.length; i++) { try {// 處理get亂碼values[i] = new String(values[i] .getBytes('ISO-8859-1'), 'utf-8'); } catch (UnsupportedEncodingException e) {e.printStackTrace(); } } }}hasEncode = true; } return parameterMap; } return super.getParameterMap(); } //取一個(gè)值 @Override public String getParameter(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; // 取回參數(shù)的第一個(gè)值 } //取所有值 @Override public String[] getParameterValues(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; }}
然后在web.xml中配置這個(gè)過濾器即可!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用CSS3新特性創(chuàng)建透明邊框三角2. spring boot整合redis實(shí)現(xiàn)RedisTemplate三分鐘快速入門3. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能4. React優(yōu)雅的封裝SvgIcon組件示例5. el-table表格動(dòng)態(tài)合并相同數(shù)據(jù)單元格(可指定列+自定義合并)6. 使用css實(shí)現(xiàn)全兼容tooltip提示框7. WML語言的基本情況8. ajax post下載flask文件流以及中文文件名問題9. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】10. springboot基于Redis發(fā)布訂閱集群下WebSocket的解決方案
