Java Web实战项目-六
上回已经搞定了登陆的问题,那么登陆之后页面就要转到首页,并将原来登陆字样改为已经登陆的用户名字样,这里主要用到的是session类。
改写LoginServlet
在登陆验证成功后将session里的用户名填入request,并执行转发:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username").trim();
String password = request.getParameter("password").trim();
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
Map<String,Object> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
List<User> us = session.selectList("getPassword",username);
User user = us.get(0);
if(user.getPassword().equals(password)){
request.getSession().setAttribute("n", username);
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
}改写Header.jsp
使用jsp的taglib自定义标签,要先引用相关的包1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%"http://java.sun.com/jsp/jstl/core" prefix="c"%> uri=
<div class="col-md-12 column" >
<ul class="nav nav-tabs">
<li style="font-size:20px;">
<a href="index.jsp">首页</a>
</li>
<c:choose>
<c:when test="${empty sessionScope.n}">
<li style="font-size:20px;">
<a href="login.jsp">登陆</a>
</li>
</c:when>
<c:otherwise>
<li style="font-size:20px;">
<a href="javascript:void(0)">欢迎您,${sessionScope.n}</a>
</li></c:otherwise></c:choose>
<li style="font-size:20px;">
<a href="#">商店</a>
</li>
</ul>
</div>