1. 程式人生 > 其它 >SpringMvc資料處理及跳轉

SpringMvc資料處理及跳轉

資料處理

處理提交資料

1、提交的域名稱和處理方法的引數名一致

提交資料 : http://localhost:8080/hello?name=cnfalltime

處理方法 :

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

後臺輸出 : cnfalltime

2、提交的域名稱和處理方法的引數名不一致

提交資料 : http://localhost:8080/hello?username=cnfalltime

處理方法 :

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

後臺輸出 : cnfalltime

3、提交的是一個物件

要求提交的表單域和物件的屬性名一致 , 引數使用物件即可

1、實體類

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
   private int id;
   private String name;
   private int age;

}

2、提交資料 : http://localhost:8080/mvc04/user?name=cnfalltime&id=1&age=23

3、處理方法 :

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

後臺輸出 : User { id=1, name='cnfalltime', age=25 }

說明:如果使用物件的話,前端傳遞的引數名和物件名必須一致,否則就是null。

資料顯示到前端

第一種 : 通過ModelAndView

public class ControllerTest1 implements Controller {//該方法為通過實現Controller介面來配置控制器,缺點是:一個控制器中只有一個方法,如果要多個方法則需要定義多個Controller;定義的方式比較麻煩;

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       //返回一個模型檢視物件
       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){
   //封裝要顯示到檢視中的資料
   //相當於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){
   //封裝要顯示到檢視中的資料
   //相當於req.setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}

對比

就對於新手而言簡單來說使用區別就是:

Model 只有寥寥幾個方法只適合用於儲存資料,簡化了新手對於Model物件的操作和理解;

ModelMap 繼承了 LinkedMap ,除了實現了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性;

ModelAndView 可以在儲存資料的同時,可以進行設定返回的邏輯檢視,進行控制展示層的跳轉。

資料亂碼處理

不得不說,亂碼問題是在我們開發中十分常見的問題,也是讓我們程式猿比較頭大的問題!

以前亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.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>

但是我們發現 , 有些極端情況下.這個過濾器對get的支援不好 .

處理方法 :

1、修改tomcat配置檔案 :設定編碼!

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

2、自定義過濾器
詳見部落格

然後在web.xml中配置這個過濾器即可!