java web基础 --- URL重定向Filter
httpRequest.getRequestDispatcher("/helloWorld").forward(httpRequest, response);
服务器端转发,不改变浏览器端URL地址,常用
httpResponse.sendRedirect(uri);
浏览器端重定向,改变URL在浏览器地址栏
URLOverWriteFilter.java
1 package com.web1.util; 2 3 import java.io.IOException; 4 5 import javax.print.attribute.standard.ReferenceUriSchemesSupported; 6 import javax.servlet.Filter; 7 import javax.servlet.FilterChain; 8 import javax.servlet.FilterConfig; 9 import javax.servlet.ServletException;10 import javax.servlet.ServletRequest;11 import javax.servlet.ServletResponse;12 import javax.servlet.annotation.WebFilter;13 import javax.servlet.http.HttpServletRequest;14 import javax.servlet.http.HttpServletResponse;15 16 /**17 * Servlet Filter implementation class URLOverWriteFilter18 */19 @WebFilter("/URLOverWriteFilter")20 public class URLOverWriteFilter implements Filter {21 22 private FilterConfig config;23 /**24 * Default constructor. 25 */26 public URLOverWriteFilter() {27 // TODO Auto-generated constructor stub28 }29 30 /**31 * @see Filter#destroy()32 */33 public void destroy() {34 // TODO Auto-generated method stub35 }36 37 /**38 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)39 */40 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {41 //do something42 String uri = "";43 HttpServletRequest httpRequest = null;44 if (request instanceof HttpServletRequest) {45 httpRequest = (HttpServletRequest)request;46 System.out.println("URL:" + httpRequest.getRequestURL().toString());47 System.out.println("URI:" + httpRequest.getRequestURI().toString());48 uri = httpRequest.getRequestURI();49 uri = uri.replace("home.html", "helloWorld");50 }51 if (httpRequest.getRequestURI().indexOf("home.html") >= 0) {52 /*if (response instanceof HttpServletResponse) {53 HttpServletResponse httpResponse = (HttpServletResponse)response;54 httpResponse.sendRedirect(uri);55 }*/56 httpRequest.getRequestDispatcher("/helloWorld").forward(httpRequest, response);57 }58 else{59 //go to next Filter60 chain.doFilter(request, response);61 }62 }63 64 /**65 * @see Filter#init(FilterConfig)66 */67 public void init(FilterConfig fConfig) throws ServletException {68 this.config = fConfig;69 }70 71 }
web.xml
按照filter-mapping的顺序
Hello World Servlet Hello World Servlet Encode Filter com.web1.util.RequestEncodeFilter Encode Filter /* URLOverFilter Filter com.web1.util.URLOverWriteFilter URLOverFilter Filter /home.html helloWorld com.web1.hello.HelloWorldServlet helloWorld /helloWorld helloImage com.web1.hello.ImageServlet helloImage /helloImage