1. 程式人生 > 其它 >SpringMVC框架(三)—資料處理和亂碼問題

SpringMVC框架(三)—資料處理和亂碼問題

資料處理

處理提交資料

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

1、處理方法 :

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

2、提交資料 : http://localhost:8080/hello?name=zhangsan
3、後臺輸出 : zhangsan

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

1、處理方法 :

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

2、提交資料 : http://localhost:8080/hello?username=zhangsan
3、後臺輸出 : zhangsan

三、提交的是一個物件

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

1、實體類

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

2、處理方法 :

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

3、提交資料 : http://localhost:8080/mvc04/user?name=zhangsan&id=1&age=15
4、後臺輸出 : User { id=1, name='zhangsan', age=15 }

資料顯示到前端

第一種:通過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;
    }
}

第二種 : 通過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

@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 可以在儲存資料的同時,可以進行設定返回的邏輯檢視,進行控制展示層的跳轉。

解決中文亂碼問題

在web.xml新增過濾器

<filter>
    <filter-name>encoding</filter-name>
    <filterclass>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>