登录Jsp页面代码如下图
<form method="post" action="/books/LoginServlet">
<label class="control-label" for="username">账 号</label>
<input type="text" id="username" name="username" placeholder="学号"/>
<input type="password" id="password" name="password" placeholder="密码"/>
<input type="submit" value="登 录"/>
</form>
LoginServlet核心代码如下图
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet(request, response);
//登录的判断
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//获取账号和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
AdminDao userdao = new AdminDao();
//对账号和密码进行判断
boolean result = userdao.Login_verify(username, password);
HttpSession session = request.getSession();
//判断输入正确
if(result){
AdminBean adminbean = new AdminBean();
AdminDao admindao = new AdminDao();
//更加账号和密码查找出读者的信息
adminbean = admindao.getAdminInfo(username,password);
//将aid存入session中
session.setAttribute("aid", ""+adminbean.getAid());
session.setAttribute("name",""+adminbean.getName());
//设置session的失效时间
session.setMaxInactiveInterval(6000);
//根据status的值来判断是管理员,还是读者,status=1为读者
if(adminbean.getStatus()==1){
request.getRequestDispatcher("/books/index2.jsp");
response.sendRedirect("/books/index2.jsp");
}else{
response.sendRedirect("/books/admin.jsp");
}
}else{
//没有找到对应的账号和密码,返回重新登录
session.setAttribute("state", "密码错误");
response.sendRedirect("/books/login.jsp");
}
}
其中,最关键的是以下几句,我们来删减一些跟本文关系不大的代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//新建session对象
HttpSession session = request.getSession();
//以键值对的形式保存在session中,前面的"name",就是键,后面getName()获取到数据之后存到值的位置,组成键值对,jsp页面就可以通过键拿到对应的值
session.setAttribute("name",""+adminbean.getName());
//设置session的失效时间
session.setMaxInactiveInterval(6000);
//跳转至需要session的页面
response.sendRedirect("/books/index2.jsp");
}
获取参数的index2.jsp页面关键代码
<a href="#" 欢迎您,${name}</a>
${session的键} 这个格式就能将session的值展现出来,${}构成el表达式
但是前提是要在jsp页面引入以下代码开启el表达式,不然你写的el表达式是不生效的
<%@page isELIgnored="false"%>
可以卸载<html>标签前
——————————————————————
仅供参考及学习