我正在使用 jsp 和 servlet 创建一个简单的 Web 系统。为了验证我的用户并检查他/她是否登录,我决定使用 cookie,因为我认为它更简单。
所以我编写了一个 servlet 来验证和保存 cookie 信息。关注代码:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
PrintWriter writer = response.getWriter();
User user = new User();
user.setLoginEmail(request.getParameter("login"));
user.setPsswd(request.getParameter("psswd"));
UserDAO dao = new UserDAO();
try {
user = dao.userAuthentication(user);
} catch (SQLException e) {
throw new RuntimeException(e);
}
if (user != null) {
Cookie login = new Cookie("login", user.getLoginEmail());
Cookie firstName = new Cookie("firstName", user.getUsername().split(" ")[0]);
Cookie lastName = new Cookie("lastName", user.getUsername().split(" ")[user.getUsername().split(" ").length - 1]);
login.setMaxAge(60 * 60 * 24);
firstName.setMaxAge(60 * 60 * 24);
lastName.setMaxAge(60 * 60 * 24);
response.addCookie(login);
response.addCookie(firstName);
response.addCookie(lastName);
writer.println("<authentication>done</authentication>");
} else {
writer.println("<authentication>fail</authentication>");
}
writer.flush();
writer.close();
}
比我在当前页面上刷新以捕获 cookie 并在页面上显示登录的用户,但是当我检查 cookie 数组为空时。关注代码:
<%
Cookie[] cookies = request.getCookies();
String name = new String();
String login = new String();
String authenticated = new String();
for (Cookie c : cookies) {
if(c.getName().equals("login")){
name = c.getValue().split("|")[0];
login = c.getValue().split("|")[1];
authenticated = c.getValue().split("|")[2];
}else{
authenticated = "NAO";
}
}
%>
<div id="principal">
<div id="login">
<%
if(authenticated.equals("SIM")){
out.println("<p>");
out.println("Welcome, <b>" + name + "</b> | <a href=\"#\" id=\"logout-link\">log out</a>");
out.println("</p>");
}else{
out.println("<p>");
out.println("<a href=\"#\" id=\"signin-link\">sign in</a> or <a id=\"create-account\" href=\"create-account.jsp\">create account</a>");
out.println("</p>");
}
%>
</div>
同一页面的 JS。
<script type="text/javascript">
$(document).ready(function() {
$("#signin-form").dialog({
autoOpen : false,
height : 235,
width : 350,
modal : true,
buttons : {
"Sign In" : function() {
signin();
$(this).dialog("close");
},
Cancel : function() {
$(this).dialog("close");
}
},
close : function() {
$(this).dialog("close");
},
show : {
effect : "slide",
duration : 300
},
hide : {
effect : "slide",
duration : 300
}
});
$("#signin-link").click(function() {
$("#signin-form").dialog("open");
});
});
function signin() {
$.post("signin", {
login : $("#txtLoginForm").val(),
psswd : $("#txtPsswdForm").val()
}, function(xml) {
if ($("authentication", xml).text() == "done") {
location.reload();
} else {
alert("Nao Logou!");
}
});
}
</script>
谁能帮帮我吗!?
非常感谢!!!