日期:2014-05-18  浏览次数:20671 次

问一个JSP中session的问题
怎么用session判断用户是否登陆,如果登陆了则跳转到grade.jsp   反之login.jsp?  
能说的详细点吗?最好有代码?
session的代码是在首页index.jsp添加还是在要跳转到的页面grade.jsp添加呢?  


------解决方案--------------------
通过session的getAttribute( "name ")和session.setAttribute( "name ",value);
登陆的时候先根据用户的名称去查询sessin里是否存在name用户,有则登陆,否则显示登陆页面,让用户输用户名和密码,处理登陆,登陆成功的时候将用户的name存入session
------解决方案--------------------
最好实现一个servlet监听器,判断一下.

例子:

import Javax.servlet.*;
import Javax.servlet.http.*;
import Java.io.*;
import Java.util.*;

public class LoginCheckFilter
extends HttpServlet implements Filter
{
private FilterConfig filterConfig;
//Handle the passed-in FilterConfig
public void init(FilterConfig filterConfig)
throws ServletException
{
this.filterConfig = filterConfig;
}

//Process the request/response pair
public void doFilter(ServletRequest request, ServletResponse response
, FilterChain filterChain)
{
try
{
//进行请求和响应的类型转换
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

boolean isValid = true;
String uriStr = httpRequest.getRequestURI().toUpperCase();

if (uriStr.indexOf( "LOGIN.jsp ") == -1 &&
uriStr.indexOf( "SWITCH.jsp ") == -1 &&
httpRequest.getSession().getAttribute( "ses_userBean ") == null)
{
isValid = false;
}
if (isValid)
{
filterChain.doFilter(request, response);
} else
{
httpResponse.sendRedirect( "/login.jsp ");
}
} catch (ServletException sx)
{
filterConfig.getServletContext().log(sx.getMessage());
} catch (IOException iox)
{
filterConfig.getServletContext().log(iox.getMessage());
}
}

//Clean up resources
public void destroy()
{
}
}


------解决方案--------------------
<%
String user = session.getAttribute( "username ");
if (user==null) {
response.sendRedirect( "login.jsp ");
} else {
response.sendRedirect( "grade.jsp ");
}
%>

------解决方案--------------------
1.不使用过滤的话
index.jsp提供登陆表单,并有一些超连接
form提交到servlet,通过查数据库确定是否是注册用户,如果是就session.setAttribute( "键 ", "值 ")然后跳转回index.jsp
用户可以通过超连接进入不同的页面,在不同的页面上include一个check.jsp,这个check.jsp主要通过判断session.getAttribute( "键 ")来确定是否是以注册用户,如果是什么也不做,不是就response.sendRedirect( "login.jsp ")
2.使用过滤的话
过滤器做check.jsp的操作,然后在配置文件中配置他要过滤的jsp

------解决方案--------------------
String strUserName = (String) session.getValue( "strUserName ");

String strPriorityOfUser = (String) session.getValue( "strPriorityOfUser ");

if (strUserName == null)
{
%>
out.println( " <SCRIPT language=javascript> alert( '请你重新登陆…… ');window.location=login.jsp '; </script> ");
<%
}
else
{