场景:需对请求的URL进行重定向
记录:NO.242
本例环境:
容器:apache-tomcat-8.5.57
jdk:1.8
本例需求:
需要重定向后,客户端无感,即浏览器URL不变。
1.forward和sendRedirect简单区分
forward方式:
使用函数:
httpServletRequest.getRequestDispatcher("/fujian/shangban").forward(httpServletRequest,httpServletResponse);
服务器内部重定向,程序收到请求后重新定向到另一个程序或者同一个程序另一个方法,客户机并不知道,在浏览器中,请求的url不会发生变化。
sendRedirect方式:
使用函数:
httpServletResponse.sendRedirect("http://localhost:8080/platform/fujian/touzi?num=1024");
服务器收到请求后发送一个状态头给客户端,客户将再请求一次,即浏览器发起了两次请求,浏览器中url会发生变化,变成重定向后的请求地址。
2.过滤器类代码
过滤器实现Filter接口。
在doFilter中根据请求URL进行转发。
代码:
public class PlatformFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
StringBuffer urlBuffer = httpServletRequest.getRequestURL();
if(urlBuffer.toString().contains("platform/work")){
//使用forward请求转发
System.out.println("过滤器doFilter中调用,forward请求转发.");
httpServletRequest.getRequestDispatcher("/fujian/shangban").forward(httpServletRequest,httpServletResponse);
return;
}else if(urlBuffer.toString().contains("platform/touzi")){
//使用sendRedirect请求转发
System.out.println("过滤器doFilter中调用,sendRedirect请求转发.");
String redirectUrl = "http://localhost:8080/platform/fujian/touzi?num=1024";
httpServletResponse.sendRedirect(redirectUrl);
return;
}
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
3.在web.xml中配置
<filter>
<filter-name>PlatformFilter</filter-name>
<filter-class>com.zbz.PlatformFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PlatformFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
4.测试类PlatformController
代码:
@RestController
@RequestMapping("/fujian")
public class PlatformController {
@GetMapping("/shangban")
public String getShangBan(String num){
System.out.println("开始上班......");
System.out.println("上班中......");
System.out.println("报酬 num = " + num + "万");
System.out.println("下班回家......");
return "Hey,GoodJob.";
}
@GetMapping("/touzi")
public String getTouzi(String num){
System.out.println("开始投资......");
System.out.println("投资互联网项目......");
System.out.println("投资分成......");
System.out.println("报酬 num = " + num + "万");
return "Hey,财富自由.";
}
}
5.测试forward
浏览器发起请求URL: http://localhost:8080/platform/work?num=32
后台实际访问URL: http://localhost:8080/platform/fujian/shangban?num=32
打印日志:
6.测sendRedirect
浏览器第一发起请求URL: http://localhost:8080/platform/touzi?num=1024
实际访问URL,即浏览器发起第二次请求URL: http://localhost:8080/platform/fujian/touzi?num=1024
打印日志:
以上,感谢。