JAva webベース---URLリダイレクトFilter

3886 ワード

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