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并测试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫