共计 1644 个字符,预计需要花费 5 分钟才能阅读完成。
第一种:办法的返回值为字符串类型
@RequestMapping("/hello") | |
public String Hello(){System.out.println("欢送"); | |
return "success"; | |
} |
返回的字符串会通过配置的视图解析器找到须要跳转的页面:
/WEB-INF/pages/success.jsp
applicationContext.xml | |
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> | |
<property name="prefix" value="/WEB-INF/pages/"></property> | |
<property name="suffix" value=".jsp"></property> | |
</bean> |
第二种:返回值是 void
这种状况下通过转发或者重定向跳转
1. 转发
转发不必向浏览器发送第二次申请,而且可能间接拜访 WEB-INF 下的 jsp 页面
@RequestMapping("testForward") | |
public void testForward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("testForward 办法执行了"); | |
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); | |
return; | |
} |
转发后地址栏不变:
2. 重定向
重定向是再次向浏览器发送申请,地址栏会扭转,显示最终拜访的页面;重定向不能拜访 WEB-INF 文件
@RequestMapping("testRedirect") | |
public void testRedirect(HttpServletRequest request,HttpServletResponse response) throws IOException {System.out.println("testRedirect 办法执行了"); | |
response.sendRedirect(request.getContextPath()+ "/redirect.jsp"); | |
} |
第三种:间接输入响应内容
@RequestMapping("testDire") | |
public void testDire(HttpServletResponse response) throws IOException { | |
// 解决中文乱码 | |
// 设置字符编码 | |
response.setCharacterEncoding("UTF-8"); | |
// 设置浏览器解析页面编码 | |
response.setContentType("text/html;charset=UTF-8"); | |
System.out.println("testDire 执行了"); | |
response.getWriter().print("你好"); | |
return; | |
} |
第四种:用关键字实现转发或者重定向(较少应用)
forward:
@RequestMapping("testForwardKey") | |
public String testForwardKey(){System.out.println("testForwardKey 办法执行了"); | |
return "forward:/WEB-INF/pages/success.jsp"; | |
} |
redirect:
@RequestMapping("testRedirectKey") | |
public String testRedirectKey(){System.out.println("testForwardKey 办法执行了"); | |
return "redirect:/redirect.jsp"; | |
} |
正文完