SpringMVC04——数据处理及跳转
结果跳转
1、ModelAndView
设置ModelAndView对象,根据view的名称,和试图解析器跳到指定的页面。
页面:{视图解析器前缀} + viewName + {视图解析器后缀}
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
controller类
public class ControllerTest implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
ServletAPI
通过设置ServletAPI,不需要视图解析器。
- 通过HTTPServletResponse进行输出
- 通过HttpServletResponse实现重定向
- 通过HttpServletResponse实现转发
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//转发
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
通过SpringMVC来实现转发和重定向(无视图解析器)
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String t1(){
//转发1
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String t2(){
//转发2
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String t3(){
//重定向
return "redirect:/index.jsp";
}
}
通过SpringMVC来实现转发和重定向(有视图解析器)
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String t1(){
//转发
return "test";
}
@RequestMapping("/rsm2/t2")
public String t2(){
//重定向
return "redirect:/index.jsp";
}
}
数据处理
处理提交的数据
1、提交的域名称和处理方法的参数一致
提交数据 : http://localhost:8080/test?name=pp
处理方法 :
@RequestMapping("/test")
public String test(String name){
System.out.println(name);
return "test";
}
2、提交的域名称和处理方法的参数名不一致
提交数据 : http://localhost:8080/test?username=pp
处理方法 :
//@RequestParam("username") : username提交的域的名称 .
@RequestMapping("/test")
public String test(@RequestParam("username") String name){
System.out.println(name);
return "test";
}
3、提交的是一个对象
要求提交的表单域和对象的属性名一致,参数使用对象即可
提交数据 : http://localhost:8080/user?name=pp&id=1&age=15
如果使用对象的话,前端传递的参数名和对象名必须一致,否则就是null
数据显示到前端
- ModelAndView(常用的)
- ModelMap
- Model(适合用于储存数据)
posted on 2021-05-05 21:15 JavaCoderPan 阅读(11) 评论(0) 编辑 收藏 举报 来源