Springmvc 重定向和转发和处理数据

在使用之前的视图解析器以外还可以使用其他方式
测试前,需要将视图解析器注释掉

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/m1")
public class ModelTest1 {
    @RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg","hello mvc");
        //转发
        return "forward:/WEB-INF/jsp/test.jsp";
    }
    @RequestMapping("/t2")
    public String test2(Model model){
        model.addAttribute("msg","hello mvc");
        //重定向
        return "redirect:/index.jsp";
    }
}

return的字符串通过两个关键字可以实现重定向和转发

处理数据

处理简单数据类型

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/t1/{name}")
    public String test1(@PathVariable String name, Model model){
        model.addAttribute("msg","你好"+name);
        return "test";
    }
}

处理类数据
处理类数据时必须保证参数名字与类的成员变量完全一致

 @RequestMapping("/t2")
    public String test2(User user, Model model){
        System.out.println(user);
        return "test";
    }

数据显示到前端

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){
   //封装要显示到视图中的数据
   //相当于req.setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}
  1. 通过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 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
posted @ 2021-04-27 20:01  一个经常掉线的人  阅读(96)  评论(0)    收藏  举报