以前没遇到过今天遇到了奇葩了,用redirect或forward跳转居然拿不到session。程序员是不允许有这种奇葩现象不明不白的出现的,如是开始了调试之路,调试了好一阵(可能太粗心了)也没找到原因,于是去网上搜了一下,出现这个问题的人还是挺多的 ,有几种类型:
1、session的过期时间设置有误
2、设置或获取session有误
而我的问题出现在计算机名 和localhost上。其实两者都映射到127.0.0.1上在host上配置了,但是chrome和tomcat把它看成了不同的域了 session被卡了一节。
简单的代码 登录---->servlet处理-->处理成功-->设置session-->跳转到main.jsp
<form class="form-signin form-horizontal" method="post" action="<%=basePath %>servlet/LoginServlet">
<div class="row">
<div class="span5">
<div class="control-group">
<label class="control-label" for="user_brchno">机构号:</label>
<div class="controls">
<input type="text" id="user_brchno" class="input-block-level typeahead" name="user_brchno" autocomplete="off" placeholder="请输入机构"></div>
</div>
<div class="control-group">
<label class="control-label" for="user_userno">柜员号:</label>
<div class="controls">
<input type="text" id="user_userno" class="input-block-level typeahead" autocomplete="off" name="user_userno" placeholder="请输入柜员号"></div>
</div>
<div class="control-group">
<label class="control-label" for="user_name">姓名:</label>
<div class="controls">
<input type="text" id="user_name" class="input-block-level typeahead" autocomplete="off" name="user_name" placeholder="请输入姓名"></div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-small btn-primary " value="登录"></div>
</div>
</div>
</div>
</form>
登录处理servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
UserWrap userWrap = new UserWrap();
User user = new User();
HttpSession session = request.getSession(true);
boolean flag = false;
try {
flag = UserWrap.login(session, request, user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (flag) {
session.setAttribute("user", user);
// RequestDispatcher rd = request.getRequestDispatcher("/main.jsp");
//rd.forward(request, response)
/*
**response.sendRedirect("http://localhost:8888/Type/main.jsp");
*/
response.sendRedirect("http://alan:8888/Type/main.jsp");
} else {
response.sendRedirect("http://localhost:8888/Type/index.jsp");
}
}
奇葩出现在我标记星号的那行
main.jsp页面
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
User user = new User();
if (session.getAttribute("user") == null) {
response.sendRedirect(basePath);
} else {
user = (User) session.getAttribute("user");
}
%>