SpringMVC结果跳转方式
ModelAndView
设置ModelAndView对象,根据view名称和视图解析器跳转到指定的页面
页面:{视图及解析器前缀} + viewName + {视图解析器后缀}
有视图解析器
- 转发
@RequestMapping("/m1/t1")
public String test1(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "admin/hello";//默认转发
}
- 重定向
@RequestMapping("/m1/t2")
public String test2(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "redirect:/index.jsp";//重定向
}
- 拼接出错
@RequestMapping("/m1/t3")
public String test3(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "redirect1:/admin/hello.jsp";//拼接出错 /WEB-INF/jsp/redirect1:/admin/hello.jsp.jsp
}
没有视图解析器
- 转发
@RequestMapping("/n1/t1")
public String test4(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "/index.jsp";//转发
}
@RequestMapping("/n1/t2")
public String test5(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "forward:/index.jsp";//转发
}
- 重定向
@RequestMapping("/n1/t3")
public String test6(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "redirect:/index.jsp";//重定向
}
接收请求参数及数据的回显
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/t1")
//接收对象 http://localhost:8080/user/t1?id=1&age=18&name=www
public String test1(User user, Model model) {
System.out.println(user);
model.addAttribute("msg", user);
return "admin/hello";
}
@RequestMapping("/t2")
//接收参数 http://localhost:8080/user/t2?username=www
public String test2(@RequestParam("username") String name, Model model) {//从前端接收的参数为username
System.out.println("接收到username:" + name);
model.addAttribute("msg", name);
return "admin/hello";
}
}
对比:
Model :方法少,只适用于存储数据,简化了新手对于Model对象的操作和理解
Model Map:继承了LinkedMap,处理实现一些自身的方法,同样的继承了LinkedMap的方法和特性
ModelAndView:可以再存储数据的同时,可以进行设置返回的逻辑视图,进行控制层的跳转
乱码问题
可以利用springMVC自带的过滤乱码
<!-- 配置springMVC乱码过滤-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>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>