SpringMVC原理分析 | 数据处理:ModelAndView-LMLPHP


重定向和转发

ModelAndView

ServletAPI

@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
}

SpringMVC

数据处理

处理提交数据

数据显示到前端

ModelAndView

//实现了Controller类说明这就是控制器
public class ControllerTest1 implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //创建模型和视图对象
        ModelAndView modelAndView = new ModelAndView();
        封装数据,向模型添加属性msg与值,可以在jsp页面取出、渲染
        modelAndView.addObject("msg","ControllerTest1");
        //视图跳转
        modelAndView.setViewName("test");

        //返回视图模型对象
        return modelAndView;
    }
}

Model

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/t1")
    public String test(@RequestParam("username") String name, Model model) {

        //接受前端参数
        System.out.println("接收到前端的参数为:" + name);

        //将放回结果传递给前端
        model.addAttribute("msg",name);

        //跳转视图
        return "test";
    }
}

ModelMap

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/t3")
    public String test3(ModelMap map){
        map.addAttribute("msg","HELLO ModelMap");
        return "test";
    }
    
}

总结

过滤器解决乱码

Javaweb过滤器

SpringMVC过滤器



SpringMVC原理分析 | 数据处理:ModelAndView-LMLPHP

06-30 12:29