SpringMVC请求转发和重定向测试
保存视图解析器的请求转发和重定向测试
1.web.xml模板文件(略)
2.springmvc配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自动扫描包,让指定包下的注解生效,有IOC容器统一管理--> <context:component-scan base-package="com.lian.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <!-- 视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 后缀--> <property name="suffix" value=".jsp"/> </bean> </beans>
3.Controller类
请求转发需要全限定路径,同时要注意重定向不能访问到WEB-INF文件下的资源
@Controller public class ResultGo { @RequestMapping("/result/t1") public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().println("Hello,Spring by servlet API!"); } @RequestMapping("/result/t2") public void test2(HttpServletRequest req,HttpServletResponse resp) throws IOException { //重定向 resp.sendRedirect("/index.jsp"); } @RequestMapping("/result/t3") public void test3(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { //请求转发 req.setAttribute("msg","/result/t3"); req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp); } }
不保存视图的请求转发和重定向测试
@Controller public class ResultGo2 { @RequestMapping("/rsm/t1") public String test1(){ //请求转发方式一 return "/index.jsp"; } @RequestMapping("/rsm/t2") public String test2(Model model){ //请求转发方式二 model.addAttribute("msg","test2请求转发"); return "forward:/WEB-INF/jsp/test.jsp"; } @RequestMapping("/rsm/t3") public String test3(Model model){ model.addAttribute("msg","test3redirect"); //重定向 return "redirect:/index.jsp";//这里重定向转不过去/WEB-INF/jsp/test.jsp,,重定向访问不到WEB-INF下的资源,访问WEB-INF/jsp/test.jsp只能通过转发的方式咯? } }
4.配置tomcat并测试
浙公网安备 33010602011771号