‘壹’ java的session用法
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;
import
javax.servlet.http.HttpSession;
import
com.fz.entity.User;
public
class
ValidatorFilter
implements
Filter
{
public
void
destroy()
{
}
public
void
doFilter(ServletRequest
arg0,
ServletResponse
arg1,
FilterChain
arg2)
throws
IOException,
ServletException
{
HttpServletRequest
request
=
(HttpServletRequest)arg0;
HttpServletResponse
response
=
(HttpServletResponse)arg1;
HttpSession
session
=
request.getSession();
User
user
=
(User)session.getAttribute("user");
//判断用户是否登录,如果没有登录,则直接重定向至登录页面,
//如果登录,则将请求交给下一个过滤器或者目标资源
if(user
==
null||user.getUserName()==null){
response.sendRedirect(request.getContextPath()+"/login.jsp");
}else{
arg2.doFilter(request,
response);
}
}
public
void
init(FilterConfig
filterConfig)
throws
ServletException
{
}
以上是filter的代码
以下是在web.xml中的配置
<filter>
<filter-name>validatorFilter</filter-name>
<filter-class>com.fz.filter.ValidatorFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>validatorFilter</filter-name>
<url-pattern>/user/*</url-pattern>
</filter-mapping>
‘贰’ java怎么获取session中所有的值
session是后台服务器端的变量,而js是前段脚本,在js中是没有现成的方法获取session的值的,需要通过服务器语言来获取。
‘叁’ java如何获取web项目中的所有session
使用一下代码来获取:
java.util.Enumeration e = request.getSession().getAttributeNames();
while( e.hasMoreElements()) {
String sessionName=(String)e.nextElement();
out.println("\nsession item name="+sessionName);
out.println("\nsession item value="+request.getSession().getAttribute(sessionName));
}
String value=String.valueOf(request.getSession().getAttribute(sessionName));
‘肆’ java中如何取项目的所有session
java.util.Enumeration e = request.getSession().getAttributeNames();
while( e.hasMoreElements()) {
String sessionName=(String)e.nextElement();
out.println("\nsession item name="+sessionName);
out.println("\nsession item value="+request.getSession().getAttribute(sessionName));
}
String value=String.valueOf(request.getSession().getAttribute(sessionName));