利用java servlet实现简单的web请求过滤和跳转

时间:2022-10-10 21:05:35

今日有两个微信web项目合并了,但是还有些链接指向废弃的项目,另外不想在服务器上运行两份相同web项目(1、影响性能、2、维护升级容易出错),因此决定写一个简单链接跳转的项目,spring的filter过滤器可以实现,但想想spring干这个有点大材小用,想到java的servlet可以支持通配符,因此用servlet写了一个简单的跳转程序,总共花了不到一小时的时间。废话少说上代码:

 1 /**
 2  * Servlet implementation class Default
 3  */
 4 @WebServlet("/*")
 5 public class Default extends HttpServlet {
 6     private static final long serialVersionUID = 1L;
 7 
 8     /**
 9      * @see HttpServlet#HttpServlet()
10      */
11     public Default() {
12         super();
13         // TODO Auto-generated constructor stub
14     }
15 
16     /**
17      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
18      *      response)
19      */
20     protected void doGet(HttpServletRequest request,
21             HttpServletResponse response) throws ServletException, IOException {
22         String thisURI = request.getRequestURL().toString();
23         String queryString = request.getQueryString();
24         String host = "112.125.121.163";
25         //String host = "localhost";
26         String oldURI = "http://" + host + ":8080/travel-core";
27         if (thisURI.indexOf(oldURI) >= 0) {
28             String newURI = thisURI.replaceAll(oldURI, "http://" + host
29                     + ":8080/travel-weixin");
30             if (queryString != null && queryString.length() > 0)
31                 newURI += "?" + queryString;
32             response.sendRedirect(newURI);
33         }
34     }
35 
36     /**
37      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
38      *      response)
39      */
40     protected void doPost(HttpServletRequest request,
41             HttpServletResponse response) throws ServletException, IOException {
42         this.doGet(request, response);
43     }
44 
45 }

注意代码第四行是关键@WebServlet("/*"),这里使用了通配符,所有的请求都会送到doGet和doPost方法里,另外要注意 request.getRequestURL()方法不能获取到queryString因此一定要request.getQueryString()获取参数,拼到新地址的后面。