结果跳转方式
1.ModelAndView
设置ModelAndView对象,根据View名称,和视图解析器,跳转到指定的页面;
页面 :{视图解析器的前缀} + viewName + {视图解析器的后缀}
// ModelAndView
@RequestMapping("/test1")
public ModelAndView test1(HttpServletRequest request, HttpServletResponse response){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","chaowenli");
mv.setViewName("test");
return mv;
}
2.ServletAPI
// 使用servletAPI
@RequestMapping("/test2")
public void test2(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("msg","chaowenli2");
response.getWriter().println("hello");
request.getRequestDispatcher("index.jsp").forward(request,response);//请求转发
response.sendRedirect("index.jsp"); //重定向
}
3.SpringMVC不带视图解析器
// 使用springmvc,不用视图解析器
@RequestMapping("/test3")
public String test3(HttpServletRequest request){
request.setAttribute("msg","chaowenli3");
// return "index.jsp"; //请求转发
return "forward:index.jsp"; //请求转发
// return "redirect:index.jsp"; //重定向
}
4.SpringMVC带视图解析器
// 使用springmvc,有视图解析器
@RequestMapping("/test4")
public String test4(){
return "test";
}
}
数据处理
处理前端传递过来的数据;
1. 名字规范的数据
@RequestMapping("/hello")
//请求参数名和处理参数名一样的情况下,我们直接接收到前端传递的数据;
//Model主要作用:为了给前端传递我们封装好的参数;
public String hello(String name, Model model){
System.out.println(name);
model.addAttribute("aaa",name);
return "test";
}
2. 名字不规范的数据
@RequestMapping("/hello2")
//请求参数名和处理参数名不一样的情况下
//状况:用户传递的参数名和我们要处理的参数名不一致,需要使用一个注解@RequestParam("username")来进行匹配
public String hello2(@RequestParam(value = "username",required = false) String name, Model model){
System.out.println(name);
model.addAttribute("aaa",name);
return "test";
}
3.传递对象
尽量规范的编程:提交表单的数据和对象的属性名一致
@RequestMapping("/hello3")
//如何传递一个对象
//要求:提交表单的数据和对象的属性名一致;参数直接使用对象即可;否则按照上面方式处理
public String hello3(User user,Model model){
System.out.println(user);
model.addAttribute("user",user);
return "test";
}
//原理:接收到前端请求参数名,匹配你传递的对象的属性;如果属性OK,使用set方法赋值,否则使用默认值;
@RequestMapping("/hello4")
public String hello4(int id,int age,String name,Model model){
User user = new User(id, name, age);
System.out.println(user);
model.addAttribute("user",user);
return "test";
}