关于页面转发的几种情况

关于页面转发的几种情况,以下通过Servlet的Filter接口实现:

 

在实际应用中一般会采取其中的一种方式来进行处理。

 

 

 

 

/*
 * @(#)ImageFilter.java	1.00	2010/03/17
 * CopyRight(C) stephen830 2010-2011, All rights reserved.
 */
package com.stephen.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author stephen
 *
 * 图片滤镜.
 * 对指定的图片请求进行过滤.
 */
public class ImageFilter implements Filter {
	
	/**
	 * 滤镜设置.
	 */
	protected FilterConfig filterConfig = null;

	/**
	 * 初始化.
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	/**
	 * 滤镜功能.
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(request instanceof HttpServletRequest){
			HttpServletRequest httpRequest = (HttpServletRequest)request;
			String imagePath = httpRequest.getRequestURL().toString().toLowerCase();
			
			//情况1
			//转发到新的url,并且会同时转发之前的request请求
			//浏览器url还是转发前的url
			RequestDispatcher rd = httpRequest.getRequestDispatcher("new_url");
			rd.forward(request,response);
			
			//情况2
			//转发,不带之前的request请求
			//浏览器url会变成转发后的url
			HttpServletResponse httpResponse = (HttpServletResponse)response;
			httpResponse.sendRedirect("new_url");
			
			//情况3
			//转发到新的Servlet(只能是Servlet),并且会同时转发之前的request请求
			//浏览器url还是转发前的url
			RequestDispatcher rd2 = this.filterConfig.getServletContext().getNamedDispatcher("OtherServlet");
			rd.forward(request,response);
		}
		chain.doFilter(request,response);
	}

	/**
	 * 释放.
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		this.filterConfig = null;
	}

}
 

 


在web.xml中加入以下配置:

 

 

	<filter>
		<filter-name>ImageFilter</filter-name>
		<filter-class>com.stephen.filter.ImageFilter</filter-class>
	</filter>
	

	
	<filter-mapping>
		<filter-name>ImageFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
 

 

 

注意: Servlet的Filter过滤器是有顺序的,如果在一个web应用中有多个Filter,那么系统会根据web.xml中的配置的先后顺序依次执行的。

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Web,xml,servlet,浏览器)