login.html登陆

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>
 	<form action="/day19/welcome.jsp" method="post">
 		<table border="1" align="center">
 			<caption><br>用户登录</caption>
 			<tr>
 				<th>用户名</th>
 				<td><input type="text" name="username"/></td>
 			</tr>
 			<tr>
 				<th>密码</th>
 				<td><input type="password" name="password"/></td>
 			</tr>
 			<tr>
 				<th>角色</th>
 				<td>
					<select name="role">
						<option value="普通用户">普通用户</option>
						<option value="管理员">管理员</option>
					</select>
 				</td>
 			</tr>
 			<tr>
 				<td colspan="2" align="center">
 					<input type="submit" value="提交"/>
 				</td>
 			</tr>
 		</table>
 	</form>
  </body>
</html>

fiter处理


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;

//对敏感目录进行认证[课堂练习1]
public class FilterDemo7 implements Filter {
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		//设置请求体编码方式
		request.setCharacterEncoding("UTF-8");
		
		//取得用户请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String role = request.getParameter("role");
		
		//判段
		if(username!=null && password!=null && role!=null && username.trim().length()>0 && password.trim().length()>0 && role.trim().length()>0){
			if("普通用户".equals(role)){
				request.setAttribute("message","欢迎普通用户<font color='blue'>"+username+"</font>登录");
				request.setAttribute("flag","user");
			}else if("管理员".equals(role)){
				request.setAttribute("message","欢迎管理员<font color='red'>"+username+"</font>登录");	
				request.setAttribute("flag","admin");
			}
			chain.doFilter(request,response);
		}
	}
	public void destroy() {
	}
}

结果显示

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	${message}<br/>
	<c:choose>
		<c:when test="${requestScope.flag=='admin'}">
			<a rel="nofollow" href="#">下载</a>
		</c:when>
		<c:otherwise>
			下载
		</c:otherwise>
	</c:choose>
  </body>
</html>

web.xml

 <filter>
  	<filter-name>FilterDemo7</filter-name>
  	<filter-class>cn.itcast.web.filter.FilterDemo7</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>FilterDemo7</filter-name>
  	<url-pattern>/welcome.jsp</url-pattern>
  </filter-mapping>