學習資源來自於嗶哩嗶哩UP遇見狂神說,一個寶藏UP大家快去關注吧!記得三連加分享,不要做白嫖黨.
SMBMS
數據庫:
項目搭建准備工作
-
搭建一個maven web項目
-
配置tomcat
-
測試項目是否能夠跑起來
-
導入項目中可能會遇到的Jar包
jsp,Servlet,mysql驅動,jstl,stander......<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
-
創建項目包結構
-
編寫實體類
ORM映射: 表-類映射
-
編寫基礎公共類
-
數據庫配置文件
db.propertiesdriver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf8&useSSL=true username=root password=123456
-
編寫數據庫的公共類(工具類)
package com.tan.dao; import java.sql.ResultSet; import java.sql.*; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; /** * @author null * @date 2020/5/19 */ //操作數據類的公共類 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,PreparedStatement preparedStatement, ResultSet resultSet,String sql, Object[] params) throws SQLException { //預編譯的sql,在后面直接執行就可以了 preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { //setObject,占位符從1開始,但是我們的數據是從0開始! preparedStatement.setObject(i + 1, params[i]); } preparedStatement.executeQuery(); return resultSet; } //編寫增刪改的公共方法 public static int execute(Connection connection,PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { //setObject,占位符從1開始,但是我們的數據是從0開始! preparedStatement.setObject(i + 1, params[i]); } int updateRows = preparedStatement.executeUpdate(); return updateRows; } //釋放資源 public static boolean closeResource(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) { boolean flag = true; if (resultSet != null) { try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; //相當於沒有釋放成功 } } if (preparedStatement != null) { try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; //相當於沒有釋放成功 } } if (connection != null) { try { connection.close(); //GC回收 connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; //相當於沒有釋放成功 } } return flag; } }
-
編寫字符編碼過濾器
public class CharacterEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=UTF-8"); chain.doFilter(request, response); } public void destroy() { } }
配置字符編碼過濾器的web.xml
<!--字符編碼過濾器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.tan.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 { PreparedStatement pstm = null; ResultSet rs = null; User user = null; public User getLoginUser(Connection connection, String userCode) throws SQLException { if (connection != null) { String sql = "select from smbms_user where userCode=?"; Object[] params = {userCode}; rs = BaseDao.execute(connection, pstm, rs, sql, params); if (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString(userCode)); user.setUserName(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(connection, pstm,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;
try {
connection = BaseDao.getConnection();
//通過業務層調用對應的具體的數據庫操作
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}
}
-
編寫Servlet
public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet----start....."); //獲取用戶的賬號密碼 String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); //和數據庫的密碼進行對比,調用業務層 UserService userService = new UserServiceImpl(); User user = userService.login(userCode, userPassword); if (user != null && userPassword.equals(user.getUserPassword())) {//查到有人可以登錄,與數據庫的密碼進行對比 //將用戶的信息放到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> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.tan.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
-
測試訪問,確保以上功能成功!
登錄功能優化
注銷功能:
思路: 移除session,返回登陸界面
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用戶的Constants.USER_SESSION
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect("/login.jsp");//返回登陸頁面
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注冊xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.tan.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登錄攔截優化
退出后仍可以直接進入,過濾器優化
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//從Session中獲取用戶
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if (user == null) {//已被移除注銷,或者登錄
response.sendRedirect("/smbms/error.jsp");
}else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
}
配置xml
<!--登錄優化過濾器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.tan.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
測試,登錄,注銷,權限,都要保證OK!
密碼修改
-
導入前端素材
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密碼修改</a></li>
-
寫項目,建議從底層向上寫
-
UserDao 接口
//修改當前用戶密碼 public int updatePwd(Connection connection, int id, String password) throws SQLException;
-
UserDao 接口實現類
@Override //修改當前用戶密碼 public int updatePwd(Connection connection, int id, String password) throws SQLException { PreparedStatement pstm = null; int execute = 0; if(connection!=null){ Object params[] = {password, id}; String sql = "update smbms_user set userPassword = ? where id = ?"; execute = BaseDao.execute(null, pstm, sql, params); BaseDao.closeResource(null, pstm, null); } return execute; } }
-
UserService層
//根據用戶ID修改密碼 public boolean updatePwd(int id, String pwd);
-
UserService層實現類
@Override public boolean updatePwd(int id, String pwd) { Connection connection = null; boolean flag = false; connection = BaseDao.getConnection(); //修改密碼 try { if (userDao.updatePwd(connection, id, pwd)>0) { flag = true; } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection, null, null); } return flag; }
-
記得實現復用,需要提取出方法
String method = req.getParameter("method"); if (method.equals("savepwd") && method != null) { this.updatePwd(req,resp); }
提取出的方法:
//寫成方法實現Servlet的復用 public void updatePwd (HttpServletRequest req, HttpServletResponse resp){ //從Session里面拿ID Object o = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); boolean flag = false; if (o != null && newpassword != null && newpassword.length() != 0) { UserServiceImpl 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 | IOException e) { e.printStackTrace(); } } }
記配置web.xml
-
測試
優化密碼修改使用Ajax
-
阿里巴巴fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
-
后台代碼修改
//驗證舊密碼
public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
//從Session里面拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");//獲取從pwdmodify.js里Ajax的參數,連接前端
//萬能的Map : 結果集
HashMap<String, String> resultMap = new HashMap<>();
if (o == null) {//Session過期或者失效了
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {//輸入的密碼為空
resultMap.put("result", "false");
} else {
String userPassword = ((User) o).getUserPassword();//Session中獲取用戶的老密碼
if (oldpassword.equals(userPassword)) {
resultMap.put("result", "true");//輸入密碼正確
} else {
resultMap.put("result", "true");//輸入密碼輸入不正確
}
}
try {
resp.setContentType("application/json");//限定為json格式
PrintWriter writer = resp.getWriter();//給個流
//使用阿里巴巴JSON工具類
/*
將Map格式轉化為JSON格式
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 調試
用戶管理實現(實在是太多,放棄做筆記了)
思路:
- 導入分頁的工具類
- 用戶列表頁面導入
1.獲取用戶數量
- UserDao
- UserDaoImpl
- UserService
- UserServiceImpl