springMVC数据的处理

1、 提交的数据处理

1.1、   提交的域名称和处理方法参数一致即可

 

处理方法

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

1.2、   如果域名称和参数不一致

 

处理方法

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

1.3、   提交的是一个对象

要求提交的表单域名称和对象的属性名一致,参数使用对象即可。

 

处理方法

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

实体类

public class User {
    private Integer id;
    private String name;
    private String pwd;
}

2、 将数据显示到UI层

2.1、通过ModelAndView——实现视图解析器

  @RequestMapping("/hello")
    public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("hello springmvc annotation");
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "hello springmvc annotation");
        mv.setViewName("hello");
        return mv;
    }
<!-- 配置视图渲染器 -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!-- 结果视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 结果视图的后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

2.2、通过ModelMap、Model——不需要视图解析器

ModelMap、Model需要作为方法的参数

    @RequestMapping("/hello")
    public String hello(@RequestParam("uname") String name, ModelMap modelMap) {
        System.out.println(name);
        modelMap.addAttribute("name", name);
        return "/index.jsp";
    }
    
    @RequestMapping("/user")
    public String user(User user, Model model) {
        System.out.println(user);
        model.addAttribute("user", user);
        return "/index.jsp";
    }

ModelAndView和Model、ModelMap的区别:

       相同点:

             都可以将数据封装显示到表示层页面中

       不同点:

             ModelAndView可以指定跳转的视图,而Model、ModelMap不能;

             ModelAndView需要视图解析器,而ModelModelMap不需要配置。

posted @ 2018-07-08 20:15  莯汐  阅读(123)  评论(0)    收藏  举报