7###实例代码
package cn.demo;
import java.io.IOException;
import java.io.Serializable;
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;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class ToolsFilter implements Filter, Serializable {
private String username;
private String password;
private static final long serialVersionUID = 1L;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("text/html; charset=utf-8");
String authValue = req.getHeader("Authorization");
if(authValue!=null){
int sepeIndex = authValue.toUpperCase().indexOf("BASIC ");
String b64UserAndPwd = authValue.substring(sepeIndex + "BASIC ".length());
String[] ss =new String(Base64.decode(b64UserAndPwd)).split(":");
String name=ss[0];
String word=ss[1];
if(username.equals(name)&&password.equals(word)){
chain.doFilter(request, response);
return;
}
}
resp.setStatus(401);
resp.addHeader("WWW-Authenticate", "Basic realm=管理工具控制台登录");
String errMsg = "<center><font size=2><b>登录失败,请检查用户名和口令。</b></font></center>";
resp.getWriter().println(errMsg);
}
@Override
public void init(FilterConfig config) throws ServletException {
username=config.getInitParameter("ADMIN_NAME");
password=config.getInitParameter("ADMIN_PASSWD");
}
}
web.xml配置
<filter>
<filter-name>tools</filter-name>
<filter-class>cn.demo.ToolsFilter</filter-class>
<init-param>
<param-name>ADMIN_NAME</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>ADMIN_PASSWD</param-name>
<param-value>admin</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>tools</filter-name>
<url-pattern>/*</url-pattern>
<!-- 没有配置dispatcher就是默认request方式的 -->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
网友评论