java取得请求url 进行301重定向


package com.wystu.filter;

import java.io.IOException;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Filter301 implements Filter {

protected String encoding = null;

protected FilterConfig filterConfig = null;

protected boolean ignore = true;


// --------------------------------------------------------- Public Methods

public void destroy() {

this.encoding = null;
this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse=(HttpServletResponse)response;
HttpServletRequest httpRequest=(HttpServletRequest)request;
//取得完整请求url-------------------
String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getServletPath() + "?" + this.codeToString(request.getQueryString());
//------------------------------------
// Conditionally select and set the http301 redirect to be used
String redirectUrl ="";
System.out.println("http://www." + httpRequest.getServerName());
if(!httpRequest.getServerName().startsWith("www.")){
redirectUrl = redirectUrl = "http://www." + httpRequest.getServerName();
if(httpRequest.getServerPort()!=80){
redirectUrl += ":" + httpRequest.getServerPort();
}
redirectUrl += httpRequest.getRequestURI();
//redirectUrl += httpRequest.getContextPath() + httpRequest.getServletPath();
if(!( httpRequest.getQueryString()==null || "".equals(httpRequest.getQueryString()) )){
redirectUrl+="?" + this.codeToString(httpRequest.getQueryString());
}
httpResponse.setStatus(301);
httpResponse.setHeader( "Location", redirectUrl);
httpResponse.setHeader( "Connection", "close" );
return;
}
System.out.println("redirectUrl="+redirectUrl);

// Pass control on to the next filter
chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException {

}
public String codeToString(String str) {
String strString = str;
try {
byte tempB[] = strString.getBytes("ISO-8859-1");
strString = new String(tempB);
return strString;
} catch (Exception e) {
return strString;
}
}
}



filter301
com.wystu.filter.Filter301


filter301
/*





[url=http://www.riaos.com]RIA知识库[/url]
[url=http://www.riaos.com]flex[/url]
[url=http://www.riaos.com]RIA[/url]

你可能感兴趣的:(Java)