日期:2014-05-19  浏览次数:20686 次

jsp中 session校验
页面:login.jsp,登录后的index.jsp,test.jsp, 以及checklogin.jsp;我想在访问index.jsp,test.jsp之前先做登录校验,登录后才能index.jsp,test.jsp,想使用@include指令引用校验页该如何实现;

代码:
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%
request.setCharacterEncoding("GBK");
String name = request.getParameter("user");
String pwd = request.getParameter("pwd");
System.out.println(name+" "+pwd);
if(name!=null&&pwd!=null){
if(name.equals("sa")&&pwd.equals("123")){
session.setAttribute("Login","OK");
response.sendRedirect("index.jsp");
}
else
{
out.println("登录失败,请重新输入。");
response.sendRedirect("error.jsp");
}
}

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <base href="<%=basePath%>">
   
  <title>My JSP </title>
  </head>
  
  <body>
  <form id="form1" name="form" method="post" action="./testSession/login.jsp">
姓名:<input type="text" name="user" />
<br>
密码: <input type="password" name="pwd" />
<br>
<input type="submit" name="sub" value="登录" />
</form>

  </body>
</html>


checklogin.jsp
<%
request.setCharacterEncoding("GBK");
String login=null;
try{
login = session.getAttribute("Login").toString();
if (login.equals("OK")) {
JOptionPane.showMessageDialog(null,"用户登录,欢迎进入主页。");
session.invalidate();
response.sendRedirect("index.jsp");
}
}catch(Exception e){
if (login==null) {
JOptionPane.showMessageDialog(null,"用户没有登录,请登录");
response.sendRedirect("login.jsp");
}
}

%>

index.jsp:
<html>
 <body>
  <%
  if(session.getAttribute("Login")==null){
  %>
  <%@include file="checklogin.jsp" %>
  <br>
  <%} %>
  welcome to index.
  </body>
</html>

test.jsp:
<html>
 <body>
  <%
  if(session.getAttribute("Login")==null){
  %>
  <%@include file="checklogin.jsp" %>
  <br>
  <%} %>
  welcome to index.
  </body>
</html>

我直接输入http://localhost:8080/test.jsp不跳回login.jsp,不知如何修改,请教?

------解决方案--------------------
写个filter
------解决方案--------------------
探讨

写个filter

------解决方案--------------------
写个filter 
类似 public class CharsetEncodingFilter implements Filter{...} 然后在web.xml里面配置一下
------解决方案--------------------