日期:2014-05-17 浏览次数:20749 次
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse=(HttpServletResponse) response;
Cookie cookie=new Cookie("com.login.name","yjm");
cookie.setPath("/");
httpResponse.addCookie(cookie);
chain.doFilter(request, response);
}
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<%
String name="";
System.out.println(request.getCookies());//第一次访问时,后台输出null,刷新一次即能输出相应内容
if(null != request.getCookies()){
Cookie[] cookie = request.getCookies();
for(int i = 0; i < cookie.length; i++)
{
if(cookie[i].getName().equals("com.login.name"))
{
name = cookie[i].getValue();
break;
}
}
}
%>
<script type="text/javascript">
alert(document.cookie);
</script>
<body>
<input type="text" name="" value="<%=name %>" /><br/>
<%=name %><br/>
<%=request.getCookies()%>
</body>