SpringMVC之數(shù)據(jù)處理

六、數(shù)據(jù)處理

目錄:處理提交數(shù)據(jù)扯躺、數(shù)據(jù)顯示到前端捉兴、亂碼問題

1.處理提交數(shù)據(jù)

1)提交的域名稱和處理方法的參數(shù)名一致。
提交數(shù)據(jù)http://localhost:8080/hello?name=ping
處理方法

@RequestMapping("/hello") 
public String hello(String name){ 
  System.out.println(name); 
  return "hello"; 
}

后臺輸出:ping
2)提交的域名稱和處理方法的參數(shù)名不一致录语。
提交數(shù)據(jù)http://localhost:8080/hello?username=ping
處理方法

//@RequestParam("username"):username提交的域的名稱
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){ 
  System.out.println(name); 
  return "hello"; 
}

后臺輸出:ping
3)提交的是對象倍啥。
要求提交的表單域和對象的屬性名一致,參數(shù)使用對象即可澎埠。
實體類

public class User { 
  private int id; 
  private String name; 
  private int age; 
  //構(gòu)造 
  //get/set 
  //tostring() 
}

提交數(shù)據(jù)http://localhost:8080/mvc/user?name=ping&id=1&age=20
處理方法

@RequestMapping("/user") 
public String user(User user){ 
  System.out.println(user); 
  return "hello"; 
}

后臺輸出:User { id=1, name='ping', age=20 }
說明:如果使用對象的話虽缕,前端傳遞的參數(shù)名和對象名必須一致,否則就是null蒲稳。

2.數(shù)據(jù)顯示到前端

1)通過ModelAndView

public class ControllerTest1 implements Controller { 
  public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { 
    //返回一個模型視圖對象 
    ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest1"); 
    mv.setViewName("test"); 
    return mv; 
  } 
}

2)通過ModelMap

@RequestMapping("/hello") 
public String hello(@RequestParam("username") String name, ModelMap model){ 
  //封裝要顯示到視圖中的數(shù)據(jù) 
  //相當于req.setAttribute("name",name); 
  model.addAttribute("name",name); 
  System.out.println(name); 
  return "hello"; 
}

3)通過Model

@RequestMapping("/ct2/hello") 
public String hello(@RequestParam("username") String name, Model model){ 
  //封裝要顯示到視圖中的數(shù)據(jù) 
  //相當于req.setAttribute("name",name); 
  model.addAttribute("msg",name); 
  System.out.println(name); 
  return "test"; 
}

3.亂碼問題

測試
①編寫一個提交的表單彼宠。

<form action="/t" method="post">
  <input type="text" name="name">
  <input type="submit">
</form>

②后臺編寫對應(yīng)的處理類鳄虱。

@Controller public class Encoding { 
  @RequestMapping("/t") 
  public String test(Model model,String name){ 
    model.addAttribute("msg",name);
    //獲取表單提交的值 
    return "test";
    //跳轉(zhuǎn)到test頁面顯示輸入的值 
  }
}

③輸入測試后產(chǎn)生亂碼。
以前亂碼問題通過過濾器解決凭峡,而SpringMVC給我們提供了一個過濾器拙已,可以在web.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>

修改了xml文件需要重啟服務(wù)器摧冀。
注意:有些極端情況下倍踪,這個過濾器對get的支持不好。
處理方法
Ⅰ修改Tomcat配置文件:設(shè)置編碼

<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1" 
                    connectionTimeout="20000" 
                    redirectPort="8443" />

Ⅱ自定義過濾器
在web.xml中配置這個過濾器即可索昂。

package com.kuang.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請求 全部亂碼的過濾器 
*/ 
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)對象 
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // 對request包裝增強 
    HttpServletRequest myrequest = new MyRequest(httpServletRequest); 
    chain.doFilter(myrequest, response); 
  }
  @Override 
  public void init(FilterConfig filterConfig) throws ServletException {
  } 
}
//自定義request對象建车,HttpServletRequest的包裝類 
class MyRequest extends HttpServletRequestWrapper { 
  private HttpServletRequest request; 
  //是否編碼的標記 
  private boolean hasEncode; 
  //定義一個可以傳入HttpServletRequest對象的構(gòu)造函數(shù),以便對其進行裝飾 
  public MyRequest(HttpServletRequest request) { 
    super(request);// super必須寫 
    this.request = request; 
  }
  // 對需要增強方法進行覆蓋 
  @Override
  public Map getParameterMap() { 
    // 先獲得請求方式 
    String method = request.getMethod(); 
    if (method.equalsIgnoreCase("post")) { 
      // post請求 
      try {
        // 處理post亂碼 
        request.setCharacterEncoding("utf-8"); 
        return request.getParameterMap(); 
      } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
      } 
    } else if (method.equalsIgnoreCase("get")) { 
      // get請求 
      Map<String, String[]> parameterMap = request.getParameterMap(); 
      if (!hasEncode) { // 確保get手動編碼邏輯只運行一次 
        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(); 
  }
  //取一個值 
  @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ù)的第一個值 
  }
  //取所有值 
  @Override 
  public String[] getParameterValues(String name) { 
    Map<String, String[]> parameterMap = getParameterMap(); 
    String[] values = parameterMap.get(name); 
    return values; 
  } 
}

總結(jié):亂碼問題需要在盡可能設(shè)置編碼的地方椒惨,都設(shè)置為統(tǒng)一編碼UTF-8缤至。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市康谆,隨后出現(xiàn)的幾起案子领斥,更是在濱河造成了極大的恐慌,老刑警劉巖沃暗,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件月洛,死亡現(xiàn)場離奇詭異,居然都是意外死亡孽锥,警方通過查閱死者的電腦和手機嚼黔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惜辑,“玉大人唬涧,你說我怎么就攤上這事∈⒊牛” “怎么了爵卒?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長撵彻。 經(jīng)常有香客問我钓株,道長,這世上最難降的妖魔是什么陌僵? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任轴合,我火速辦了婚禮,結(jié)果婚禮上碗短,老公的妹妹穿的比我還像新娘受葛。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布总滩。 她就那樣靜靜地躺著纲堵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪闰渔。 梳的紋絲不亂的頭發(fā)上席函,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機與錄音冈涧,去河邊找鬼茂附。 笑死,一個胖子當著我的面吹牛督弓,可吹牛的內(nèi)容都是我干的营曼。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼愚隧,長吁一口氣:“原來是場噩夢啊……” “哼蒂阱!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起狂塘,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤录煤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后睹耐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辐赞,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡部翘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年硝训,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片新思。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡窖梁,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出夹囚,到底是詐尸還是另有隱情纵刘,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布荸哟,位于F島的核電站假哎,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏鞍历。R本人自食惡果不足惜舵抹,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望劣砍。 院中可真熱鬧惧蛹,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至靠娱,卻和暖如春沧烈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背饱岸。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工掺出, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人苫费。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓汤锨,卻偏偏與公主長得像,于是被迫代替她去往敵國和親百框。 傳聞我的和親對象是個殘疾皇子闲礼,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容