httpRequest.getRequestDispatcher("/helloWorld").forward(httpRequest, response);
服务器端转发,不改变浏览器端URL地址,常用
httpResponse.sendRedirect(uri);
浏览器端重定向,改变URL在浏览器地址栏
URLOverWriteFilter.java
package com.web1.util;
import java.io.IOException;
import javax.print.attribute.standard.ReferenceUriSchemesSupported;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class URLOverWriteFilter
*/
@WebFilter("/URLOverWriteFilter")
public class URLOverWriteFilter implements Filter {
private FilterConfig config;
/**
* Default constructor.
*/
public URLOverWriteFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//do something
String uri = "";
HttpServletRequest httpRequest = null;
if (request instanceof HttpServletRequest) {
httpRequest = (HttpServletRequest)request;
System.out.println("URL:" + httpRequest.getRequestURL().toString());
System.out.println("URI:" + httpRequest.getRequestURI().toString());
uri = httpRequest.getRequestURI();
uri = uri.replace("home.html", "helloWorld");
}
if (httpRequest.getRequestURI().indexOf("home.html") >= 0) {
/*if (response instanceof HttpServletResponse) {
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpResponse.sendRedirect(uri);
}*/
httpRequest.getRequestDispatcher("/helloWorld").forward(httpRequest, response);
}
else{
//go to next Filter
chain.doFilter(request, response);
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
this.config = fConfig;
}
}
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