搭建一個Maven項目、html
配置Tomcat前端
測試項目可否跑起來java
導入項目所需的jar包(servlet,jsp,mysql,jstl,standard.....)mysql
建立項目包結構web
編寫實體類(ORM映射:表---類映射)ajax
編寫基礎公共類(數據庫配置文件)sql
driver=com.mysql.jdbc.driver url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8 user=root password=123456
編寫操做數據庫的公共類數據庫
//操做數據庫的公共類 public class BaseDao { private static String driver; private static String url; private static String username; private static String password; //靜態代碼塊類加載的時候就初始化 static { Properties properties = new Properties(); //經過類加載器加載資源 InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } driver=properties.getProperty("driver"); url=properties.getProperty("url"); username=properties.getProperty("username"); password=properties.getProperty("password"); } //獲取數據庫的鏈接 public static Connection getConnection(){ Connection connection = null; try { Class.forName("driver"); connection = DriverManager.getConnection("url", "username", "password"); } catch (Exception e) { e.printStackTrace(); } return connection; } //編寫查詢公共類 public static ResultSet execute(Connection connection,String sql,PreparedStatement ps,Object[] params,ResultSet resultSet) throws SQLException { //預編譯的sql在後面直接執行就能夠了 ps = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1,params[i]); } resultSet = ps.executeQuery(); return resultSet; } //編寫增刪改公共方法 public static int execute(Connection connection,String sql,PreparedStatement ps,Object[] params) throws SQLException { ps = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1,params[i]); } int updaterows = ps.executeUpdate(); return updaterows; } //釋放鏈接 public static boolean close(Connection connection,PreparedStatement ps,ResultSet resultSet){ boolean flag=true; if (resultSet!=null){ try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (ps!=null){ try { ps.close(); //GC回收 ps = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (connection!=null){ try { connection.close(); //GC回收 connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; }java } return flag; } }
編寫字符編碼過濾器json
public class CharacterEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); filterChain.doFilter(request,response); } public void destroy() { } }
配置web.xml數組
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
導入靜態資源
編寫前端
設置首頁
<!-- 設置歡迎界面--> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list>
編寫dao層登陸用戶的接口
public interface UserDao { //獲得登陸的用戶 public User getLoginUser(Connection connection,String userCode) throws SQLException; }
編寫dao接口的實現類
public class UserDaoImpl implements UserDao{ public User getLoginUser(Connection connection, String userCode) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; User user = null; if (connection!=null){ String sql = "select * from smbms_user where userCode=?"; Object[] params={userCode}; rs = BaseDao.execute(connection, ps, rs, sql, params); if (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setUserPassword(rs.getString("userPassword")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setAddress(rs.getString("address")); user.setUserRole(rs.getInt("userRole")); user.setCreatedBy(rs.getInt("createdBy")); user.setCreationDate(rs.getTimestamp("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate")); } BaseDao.closeResource(null,ps,rs); } return user; } }
業務層接口
public interface UserService { //用戶登陸 public User login(String userCode,String password); }
業務層實現類
public class UserServiceImpl implements UserService{ //業務層都會調用dao層 因此咱們要引用dao層 private UserDao userDao; public UserServiceImpl(){ userDao = new UserDaoImpl(); } public User login(String userCode, String password) { Connection connection = null; User user = null; connection = BaseDao.getConnection(); try { //經過業務層調用具體的業務操做 user = userDao.getLoginUser(connection,userCode); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return user; } //單元測試 @Test public void Test(){ UserServiceImpl userService = new UserServiceImpl(); User admin = userService.login("admin", "1234567"); System.out.println(admin.getUserPassword()); } }
編寫Servlet
public class LoginServlet extends HttpServlet { //Serclet控制層,調用業務層代碼 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet.start"); //獲取用戶名和密碼 String username = req.getParameter("userCode"); String password = req.getParameter("userPassword"); //和數據庫中的密碼進行對比,調用業務層 UserServiceImpl userService = new UserServiceImpl(); User user = userService.login(username, password); //把登陸的人查出來 if(user!=null){ //將用戶的信息放到session中 req.getSession().setAttribute(Constants.USER_SESSION,user); //跳轉到內部的首頁 resp.sendRedirect("jsp/frame.jsp"); }else { //轉發回登陸頁面,提示用戶名或者密碼錯誤 req.setAttribute("error","用戶名或密碼不正確!"); req.getRequestDispatcher("login.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
註冊Servlet
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.zr.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
測試訪問
註銷功能:移除session,返回登陸頁面
註銷Servlet
public class LoginoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //移除Session req.getSession().removeAttribute(Constants.USER_SESSION); //返回登陸頁面 resp.sendRedirect(req.getContextPath()+"/login.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
web.xml
<servlet> <servlet-name>LoginoutServlet</servlet-name> <servlet-class>com.zr.servlet.user.LoginoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginoutServlet</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping>
登陸攔截優化
編寫過濾器
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse respone = (HttpServletResponse) resp; //從Session中獲取用戶 User user = (User)request.getSession().getAttribute(Constants.USER_SESSION); if(user==null){ respone.sendRedirect(request.getContextPath()+"/error.jsp"); }else { filterChain.doFilter(req,resp); } } public void destroy() { } }
web.xml
<!-- 用戶登陸過濾器--> <filter> <filter-name>SysFilter</filter-name> <filter-class>com.zr.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping>
編寫dao層接口
//修改當前用戶的密碼 public int updatePwd(Connection connection,int id,String password) throws SQLException;
編寫dao接口的實現類
//修改當前用戶的密碼 public int updatePwd(Connection connection, int id, String password) throws SQLException { PreparedStatement ps = null; int count = 0; if (connection!=null){ String sql = "update smbms_user set userPassword = ? where id = ?"; Object[] param = {password,id}; count = BaseDao.execute(connection, ps, sql, param); BaseDao.closeResource(null,ps,null); } return count; }
業務層
//修改密碼 public boolean updatePwd(int id, String password);
業務層接口
public boolean updatePwd(int id, String password) { Connection connection = null; boolean flag = false; try { connection = BaseDao.getConnection(); //修改密碼 if (userDao.updatePwd(connection, id, password)>0){ flag = true; } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return flag; }
Servlet層
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取Session(用Session獲取當前用戶的id) Object o = req.getSession().getAttribute(Constants.USER_SESSION); //獲取前端輸入的密碼 String newPassword = req.getParameter("newpassword"); boolean flag = false; System.out.println("=============="); System.out.println(((User)o).getId()); System.out.println(((User)o).getUserPassword()); System.out.println(newPassword); if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User) o).getId(), newPassword); if (flag){ req.setAttribute("message","密碼修改爲功,請從新登陸!"); //密碼修改爲功,清除Session req.getSession().removeAttribute(Constants.USER_SESSION); } else { req.setAttribute("message","密碼修改失敗!"); } }else{ req.setAttribute("message","新密碼格式錯誤!"); } req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
web.xml
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.zr.servlet.user.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/jsp/user.do</url-pattern> </servlet-mapping>
在Servlet層驗證(將驗證和修改密碼提取成方法,在Servlet中調用)導入阿里巴巴fastjson的jar包
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if (method.equals("savepwd")&&method!=null){ this.updatePwd(req,resp); }else if (method.equals("pwdmodify")&&method!=null){ this.pwdModify(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //修改密碼 public void updatePwd(HttpServletRequest req, HttpServletResponse resp){ //獲取Session(用Session獲取當前用戶的id) Object o = req.getSession().getAttribute(Constants.USER_SESSION); //獲取前端輸入的密碼 String newPassword = req.getParameter("newpassword"); boolean flag = false; System.out.println("=============="); System.out.println(((User)o).getId()); System.out.println(((User)o).getUserPassword()); System.out.println(newPassword); if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User) o).getId(), newPassword); if (flag){ req.setAttribute("message","密碼修改爲功,請從新登陸!"); //密碼修改爲功,清除Session req.getSession().removeAttribute(Constants.USER_SESSION); } else { req.setAttribute("message","密碼修改失敗!"); } }else{ req.setAttribute("message","新密碼格式錯誤!"); } try { req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //驗證舊密碼 Session中有用戶的密碼 public void pwdModify(HttpServletRequest req, HttpServletResponse resp){ Object o = req.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = req.getParameter("oldpassword"); System.out.println(oldpassword); System.out.println("+++++++++++++++++++"); //萬能的Map:結果集 Map<String, String> resultMap = new HashMap<String,String>(); //Session失效 if (o==null){ resultMap.put("result","sessionerror"); }else if (StringUtils.isNullOrEmpty(oldpassword)){//輸入的密碼爲空 resultMap.put("result","error"); }else { String userPassword = ((User) o).getUserPassword();//session中用戶的密碼 if (oldpassword.equals(userPassword)){ resultMap.put("result","true"); }else { resultMap.put("result","false"); } } try { resp.setContentType("aplication/json"); PrintWriter writer = resp.getWriter(); //格式轉換 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
導入分頁的工具類,用戶列表頁面導入
UserDao
//查詢用戶總數 public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
UserDaoImpl、
//根據用戶名或角色查詢人數 public int getUserCount(Connection connection, String username, int userRole) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; int count = 0; //人數 if (connection!=null){ StringBuffer sql = new StringBuffer(); sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id"); ArrayList<Object> list = new ArrayList<Object>(); //存傳入的參數 if (!StringUtils.isNullOrEmpty(username)){ sql.append(" and u.username like ?"); list.add("%"+username+"%"); } if (userRole>0){ sql.append(" and u.userRole=?"); list.add(userRole); } System.out.println(list+"======="); Object[] params = list.toArray(); //轉化爲數組 System.out.println("UserDaoImpl--->getUserCount"+sql.toString()); System.out.println(params); rs = BaseDao.execute(connection, ps, rs, sql.toString(), params); if (rs.next()){ count = rs.getInt("count"); } BaseDao.closeResource(null,ps,rs); } return count; }
UserService
//查詢用戶的人數 public int getCountUser(String username,int userRole);
UserServiceImpl
//用戶總數 public int getCountUser(String username, int userRole) { Connection connection = null; int count = 0; try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, username, userRole); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return count; }
UserDao
//經過條件查詢userList public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize) throws SQLException;
UserDaoImpl
//經過條件查詢userList public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; //返回的用戶列表 ArrayList<User> userList = new ArrayList<User>(); if (connection!=null){ StringBuffer sql = new StringBuffer(); sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id"); //存傳入的參數 ArrayList<Object> list = new ArrayList<Object>(); if (!StringUtils.isNullOrEmpty(username)){ sql.append(" and u.username like ?"); list.add("%"+username+"%"); } if (userRole>0){ sql.append(" and u.userRole=?"); list.add(userRole); } sql.append(" order by u.creationDate DESC limit ?,?"); currentPageNo = (currentPageNo-1)*pageSize; list.add(currentPageNo); list.add(pageSize); Object[] params = list.toArray(); System.out.println("sql-->"+sql.toString()); rs = BaseDao.execute(null, ps, rs, sql.toString(), params); while (rs.next()){ User user2 = new User(); user2.setId(rs.getInt("id")); user2.setUserCode(rs.getString("userCode")); user2.setUserName(rs.getString("userName")); user2.setGender(rs.getInt("gender")); user2.setBirthday(rs.getDate("birthday")); user2.setPhone(rs.getString("phone")); user2.setUserRole(rs.getInt("userRole")); user2.setUserRoleName(rs.getString("userRoleName")); userList.add(user2); } BaseDao.closeResource(null,ps,rs); } return userList; }
UserService
//經過條件查詢userList public List<User> getUserList(String queryUsername,int queryUserRole,int currentPageNo,int pageSize);
UserServiceImpl
//經過條件查詢userList public List<User> getUserList(String queryUsername, int queryUserRole, int currentPageNo, int pageSize) { Connection connection = null; List<User> userList = null; try { connection = BaseDao.getConnection(); userList = userDao.getUserList(connection, queryUsername, queryUserRole, currentPageNo, pageSize); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return userList; }
RoleDao
public interface RoleDao { //獲取角色列表 public List<Role> getRoleList(Connection connection) throws SQLException; }
RoleDaoImpl
public class RoleDaoImpl implements RoleDao{ //獲取角色列表 public List<Role> getRoleList(Connection connection) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; List<Role> roleList = new ArrayList<Role>(); if (connection!=null){ String sql = "select * from smbms_role"; Object[] params = {}; rs = BaseDao.execute(connection, ps, rs, sql, params); while (rs.next()){ Role role = new Role(); role.setId(rs.getInt("id")); role.setRoleCode(rs.getString("roleCode")); role.setRoleName(rs.getString("roleName")); roleList.add(role); } BaseDao.closeResource(null,ps,rs); } return roleList; } }
RoleService
public interface RoleService { //獲取角色列表 public List<Role> getRoleList() ; }
RoleServiceImpl
public class RoleServiceImpl implements RoleService{ private RoleDao roleDao; public RoleServiceImpl(){ roleDao = new RoleDaoImpl(); } public List<Role> getRoleList() { Connection connection = null; List<Role> roleList = null; try { connection = BaseDao.getConnection(); roleList = roleDao.getRoleList(connection); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return roleList; } }