搭建Spring+Springmvc+jdbc框架,实现用户登录和注销功能

为什么要学习这个框架,因为在实际的项目开发中,大多都是互联网项目,现在这些项目对性能的要求比较高,所以有必要学习一下这个框架。

首先是项目的整体结构:

 

 login.html

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head lang="en">
 6     <meta charset="UTF-8">
 7     <title>系统登录 - 超市订单管理系统</title>
 8     <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css" />
 9     <script type="text/javascript">
10     /* if(top.location!=self.location){
11           top.location=self.location;
12      } */
13     </script>
14 </head>
15 <body class="login_bg">
16     <section class="loginBox">
17         <header class="loginHeader">
18             <h1>超市订单管理系统</h1>
19         </header>
20         <section class="loginCont">
21             <form class="loginForm" action="${pageContext.request.contextPath }/user/doLogin.html"  name="actionForm" id="actionForm"  method="post" >
22                 <div class="info">${error }</div>
23                 <div class="inputbox">
24                     <label for="user">用户名:</label>
25                     <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
26                 </div>    
27                 <div class="inputbox">
28                     <label for="mima">密码:</label>
29                     <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
30                 </div>    
31                 <div class="subBtn">
32                     <input type="submit" value="登录"/>
33                     <input type="reset" value="重置"/>
34                 </div>    
35             </form>
36         </section>
37     </section>
38 </body>
39 </html>      

foot.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 
 4 <footer class="footer">
 5     版权归北大青鸟
 6 </footer>
 7 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/time.js"></script>
 8 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/jquery-1.8.3.min.js"></script>
 9 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/common.js"></script>
10 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/calendar/WdatePicker.js"></script>
11 </body>
12 </html>

head.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>    
 5 <!DOCTYPE html>
 6 <html>
 7 <head lang="en">
 8     <meta charset="UTF-8">
 9     <title>超市订单管理系统</title>
10     <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css" />
11     <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/public.css" />
12 </head>
13 <body>
14 <!--头部-->
15     <header class="publicHeader">
16         <h1>超市订单管理系统</h1>
17         <div class="publicHeaderR">
18             <p><span>下午好!</span><span style="color: #fff21b"> ${userSession.userName }</span> , 欢迎你!</p>
19             <a href="${pageContext.request.contextPath }/jsp/logout.do">退出</a>
20         </div>
21     </header>
22 <!--时间-->
23     <section class="publicTime">
24         <span id="time">2015年1月1日 11:11  星期一</span>
25         <a href="#">温馨提示:为了能正常浏览,请使用高版本浏览器!(IE10+)</a>
26     </section>
27  <!--主体内容-->
28  <section class="publicMian ">
29      <div class="left">
30          <h2 class="leftH2"><span class="span1"></span>功能列表 <span></span></h2>
31          <nav>
32              <ul class="list">
33                  <li ><a href="${pageContext.request.contextPath }/jsp/bill.do?method=query">订单管理</a></li>
34               <li><a href="${pageContext.request.contextPath }/jsp/provider.do?method=query">供应商管理</a></li>
35               <li><a href="${pageContext.request.contextPath }/jsp/user.do?method=query">用户管理</a></li>
36               <li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li>
37               <li><a href="${pageContext.request.contextPath }/jsp/logout.do">退出系统</a></li>
38              </ul>
39          </nav>
40      </div>
41      <input type="hidden" id="path" name="path" value="${pageContext.request.contextPath }"/>
42      <input type="hidden" id="referer" name="referer" value="<%=request.getHeader("Referer")%>"/>

frame.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@include file="/WEB-INF/jsp/common/head.jsp"%>
 3     <div class="right">
 4         <img class="wColck" src="${pageContext.request.contextPath }/statics/images/clock.jpg" alt=""/>
 5         <div class="wFont">
 6             <h2>${userSession.userName }</h2>
 7             <p>欢迎来到超市订单管理系统!</p>
 8         </div>
 9     </div>
10 </section>
11 <%@include file="/WEB-INF/jsp/common/foot.jsp" %>

UserController.java

 1 package cn.smbms.controller;
 2 import javax.annotation.Resource;
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpSession;
 5 
 6 import org.apache.log4j.Logger;
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestMethod;
10 import org.springframework.web.bind.annotation.RequestParam;
11 
12 import cn.smbms.tools.Constants;
13 
14 import cn.smbms.pojo.User;
15 import cn.smbms.service.user.UserService;
16 
17 @Controller
18 @RequestMapping("/user")
19 public class UserController{
20     private Logger logger = Logger.getLogger(UserController.class);
21     @Resource
22     private UserService userService;
23 /*    @RequestMapping({"/welcome","/"})
24     public String welcome(String username){
25         logger.info("welcome, username:" + username);
26         return "index";
27     }*/
28     @RequestMapping(value="/login.html")
29     public String login(){
30         logger.info("进入UserController   login==========");
31         return "login";//要跳转到的逻辑视图
32     }
33     //实现用户的登录
34     //如果用户登录成功之后,将用户信息放在session中
35     //如果用户登陆失败,将用户页面录入的信息放入到request作用域中
36     @RequestMapping(value="/doLogin.html",method=RequestMethod.POST)
37     public String doLogin(@RequestParam String userCode,@RequestParam String userPassword,HttpSession session,HttpServletRequest request){
38         logger.info("进入UserController   doLogin==========");
39         //调用service方法进行用户匹配
40         User user = userService.login(userCode, userPassword);
41         if(user==null){
42             //如果用户登陆失败的话,跳转到登录页面
43             request.setAttribute("error", "用户名或密码不正确");
44             return "login";
45         }else{
46             session.setAttribute(Constants.USER_SESSION, user);
47             return "redirect:/user/main.html";
48         }
49     
50     }
51     
52     @RequestMapping(value="main.html")
53     public String main(HttpSession session){
54         //用session进行判断,如果session中有值,则可以让其进行跳转到系统首页面
55         //如果session中没有值,则让用户继续跳转到系统登陆页面
56         if(session.getAttribute(Constants.USER_SESSION)==null){
57             return "redirect:/user/login.html";
58         }
59         logger.info("进入UserController   doLogin==========");
60         return "frame";
61     }
62 }

UserDao.java

/**
* 通过userCode获取User
* @param connection
* @param userCode
* @return
* @throws Exception
*/
public User getLoginUser(Connection connection,String userCode)throws Exception;

 

UserDaoImpl.java

 1     @Override
 2     public User getLoginUser(Connection connection, String userCode)
 3             throws Exception {
 4         // TODO Auto-generated method stub
 5         PreparedStatement pstm = null;
 6         ResultSet rs = null;
 7         User user = null;
 8         if(null != connection){
 9             String sql = "select * from smbms_user where userCode=?";
10             Object[] params = {userCode};
11             rs = BaseDao.execute(connection, pstm, rs, sql, params);
12             if(rs.next()){
13                 user = new User();
14                 user.setId(rs.getInt("id"));
15                 user.setUserCode(rs.getString("userCode"));
16                 user.setUserName(rs.getString("userName"));
17                 user.setUserPassword(rs.getString("userPassword"));
18                 user.setGender(rs.getInt("gender"));
19                 user.setBirthday(rs.getDate("birthday"));
20                 user.setPhone(rs.getString("phone"));
21                 user.setAddress(rs.getString("address"));
22                 user.setUserRole(rs.getInt("userRole"));
23                 user.setCreatedBy(rs.getInt("createdBy"));
24                 user.setCreationDate(rs.getTimestamp("creationDate"));
25                 user.setModifyBy(rs.getInt("modifyBy"));
26                 user.setModifyDate(rs.getTimestamp("modifyDate"));
27             }
28             BaseDao.closeResource(null, pstm, rs);
29         }
30         return user;
31     }

UserService.java

1     /**
2      * 用户登录
3      * @param userCode
4      * @param userPassword
5      * @return
6      */
7     public User login(String userCode,String userPassword);

UserServiceImpl.java

  1 package cn.smbms.service.user;
  2 
  3 import java.sql.Connection;
  4 import java.sql.SQLException;
  5 import java.util.List;
  6 
  7 import javax.annotation.Resource;
  8 
  9 import org.springframework.stereotype.Service;
 10 import cn.smbms.dao.BaseDao;
 11 import cn.smbms.dao.user.UserDao;
 12 import cn.smbms.dao.user.UserDaoImpl;
 13 import cn.smbms.pojo.User;
 14 
 15 /**
 16  * service层捕获异常,进行事务处理
 17  * 事务处理:调用不同dao的多个方法,必须使用同一个connection(connection作为参数传递)
 18  * 事务完成之后,需要在service层进行connection的关闭,在dao层关闭(PreparedStatement和ResultSet对象)
 19  * @author Administrator
 20  *
 21  */
 22 @Service
 23 public class UserServiceImpl implements UserService{
 24     @Resource
 25     private UserDao userDao;
 26     //因为加上了注解之后,下面的这段代码就不需要了,可以注释掉,现在已经创建了new UserDaoImpl()
 27     /*public UserServiceImpl(){
 28         userDao = new UserDaoImpl();
 29     }*/
 30     @Override
 31     public boolean add(User user) {
 32         // TODO Auto-generated method stub
 33         
 34         boolean flag = false;
 35         Connection connection = null;
 36         try {
 37             connection = BaseDao.getConnection();
 38             connection.setAutoCommit(false);//开启JDBC事务管理
 39             int updateRows = userDao.add(connection,user);
 40             connection.commit();
 41             if(updateRows > 0){
 42                 flag = true;
 43                 System.out.println("add success!");
 44             }else{
 45                 System.out.println("add failed!");
 46             }
 47             
 48         } catch (Exception e) {
 49             // TODO Auto-generated catch block
 50             e.printStackTrace();
 51             try {
 52                 System.out.println("rollback==================");
 53                 connection.rollback();
 54             } catch (SQLException e1) {
 55                 // TODO Auto-generated catch block
 56                 e1.printStackTrace();
 57             }
 58         }finally{
 59             //在service层进行connection连接的关闭
 60             BaseDao.closeResource(connection, null, null);
 61         }
 62         return flag;
 63     }
 64     @Override
 65     public User login(String userCode, String userPassword) {
 66         // TODO Auto-generated method stub
 67         Connection connection = null;
 68         User user = null;
 69         try {
 70             connection = BaseDao.getConnection();
 71             user = userDao.getLoginUser(connection, userCode);
 72         } catch (Exception e) {
 73             // TODO Auto-generated catch block
 74             e.printStackTrace();
 75         }finally{
 76             BaseDao.closeResource(connection, null, null);
 77         }
 78         
 79         //匹配密码
 80         if(null != user){
 81             if(!user.getUserPassword().equals(userPassword))
 82                 user = null;
 83         }
 84         
 85         return user;
 86     }
 87     @Override
 88     public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo, int pageSize) {
 89         // TODO Auto-generated method stub
 90         Connection connection = null;
 91         List<User> userList = null;
 92         System.out.println("queryUserName ---- > " + queryUserName);
 93         System.out.println("queryUserRole ---- > " + queryUserRole);
 94         System.out.println("currentPageNo ---- > " + currentPageNo);
 95         System.out.println("pageSize ---- > " + pageSize);
 96         try {
 97             connection = BaseDao.getConnection();
 98             userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);
 99         } catch (Exception e) {
100             // TODO Auto-generated catch block
101             e.printStackTrace();
102         }finally{
103             BaseDao.closeResource(connection, null, null);
104         }
105         return userList;
106     }
107     @Override
108     public User selectUserCodeExist(String userCode) {
109         // TODO Auto-generated method stub
110         Connection connection = null;
111         User user = null;
112         try {
113             connection = BaseDao.getConnection();
114             user = userDao.getLoginUser(connection, userCode);
115         } catch (Exception e) {
116             // TODO Auto-generated catch block
117             e.printStackTrace();
118         }finally{
119             BaseDao.closeResource(connection, null, null);
120         }
121         return user;
122     }
123     @Override
124     public boolean deleteUserById(Integer delId) {
125         // TODO Auto-generated method stub
126         Connection connection = null;
127         boolean flag = false;
128         try {
129             connection = BaseDao.getConnection();
130             if(userDao.deleteUserById(connection,delId) > 0)
131                 flag = true;
132         } catch (Exception e) {
133             // TODO Auto-generated catch block
134             e.printStackTrace();
135         }finally{
136             BaseDao.closeResource(connection, null, null);
137         }
138         return flag;
139     }
140     @Override
141     public User getUserById(String id) {
142         // TODO Auto-generated method stub
143         User user = null;
144         Connection connection = null;
145         try{
146             connection = BaseDao.getConnection();
147             user = userDao.getUserById(connection,id);
148         }catch (Exception e) {
149             // TODO: handle exception
150             e.printStackTrace();
151             user = null;
152         }finally{
153             BaseDao.closeResource(connection, null, null);
154         }
155         return user;
156     }
157     @Override
158     public boolean modify(User user) {
159         // TODO Auto-generated method stub
160         Connection connection = null;
161         boolean flag = false;
162         try {
163             connection = BaseDao.getConnection();
164             if(userDao.modify(connection,user) > 0)
165                 flag = true;
166         } catch (Exception e) {
167             // TODO Auto-generated catch block
168             e.printStackTrace();
169         }finally{
170             BaseDao.closeResource(connection, null, null);
171         }
172         return flag;
173     }
174     @Override
175     public boolean updatePwd(int id, String pwd) {
176         // TODO Auto-generated method stub
177         boolean flag = false;
178         Connection connection = null;
179         try{
180             connection = BaseDao.getConnection();
181             if(userDao.updatePwd(connection,id,pwd) > 0)
182                 flag = true;
183         }catch (Exception e) {
184             // TODO: handle exception
185             e.printStackTrace();
186         }finally{
187             BaseDao.closeResource(connection, null, null);
188         }
189         return flag;
190     }
191     @Override
192     public int getUserCount(String queryUserName, int queryUserRole) {
193         // TODO Auto-generated method stub
194         Connection connection = null;
195         int count = 0;
196         System.out.println("queryUserName ---- > " + queryUserName);
197         System.out.println("queryUserRole ---- > " + queryUserRole);
198         try {
199             connection = BaseDao.getConnection();
200             count = userDao.getUserCount(connection, queryUserName,queryUserRole);
201         } catch (Exception e) {
202             // TODO Auto-generated catch block
203             e.printStackTrace();
204         }finally{
205             BaseDao.closeResource(connection, null, null);
206         }
207         return count;
208     }
209     
210 }

ConstantManager.java

 1 package cn.smbms.tools;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Properties;
 6 
 7 //读取配置文件的工具类-单例模式
 8 public class ConfigManager {
 9     //创建私有的静态变量,饿汉模式,类加载的时候,就完成初始化操作
10     private static ConfigManager configManager=new ConfigManager();
11     private static Properties properties;
12     //私有构造器-读取数据库配置文件
13     private ConfigManager(){
14         String configFile = "database.properties";
15         properties = new Properties();
16         InputStream is = 
17                 ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
18         try {
19             properties.load(is);
20             is.close();
21         } catch (IOException e) {
22             // TODO Auto-generated catch block
23             e.printStackTrace();
24         }
25     }
26     //全局访问点
27     /*public static synchronized ConfigManager getInstance(){
28         if(configManager == null){
29             configManager = new ConfigManager();
30         }
31         return configManager;
32     }
33     */
34     public static  ConfigManager getInstance(){
35             return configManager;
36         }
37         
38     public String getValue(String key){
39         return properties.getProperty(key);
40     }
41 }

Constants.java

1 package cn.smbms.tools;
2 
3 public class Constants {
4     public final static String USER_SESSION = "userSession";
5     public final static String SYS_MESSAGE = "message";
6     public final static int pageSize = 5;
7 }

 

运行结果:

 

 

 

 




posted on 2020-01-21 16:18  ~码铃薯~  阅读(1153)  评论(0编辑  收藏  举报

导航