專案搭建

  • 專案連結https://gitee.com/zhangjzm/smbms.git
  • 前置知識,Servlet JSP

結構圖

搭建maven web專案

  • 1.搭建一個maven web專案

  • 2.配置tomcat

  • 3.測試專案是否能跑起來

  • 4.匯入專案中遇到的jar包

    • jsp,servlet,mysql驅動,jstl,standard
  • 5.建立專案包結構

  • 6.編寫實體類

    • ORM對映:表-類對映
  • 7.編寫基礎公共類

    • 1)資料庫配置檔案
    • 2)編寫資料庫的公共類
  • ------四部曲,1.使用Properties(IO流)獲取連線資料 2.進行連線 3.執行體(ResultSet或int) 4.關閉流

  • Properties物件類似Key Value取值

  • InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");

  • 類載入器 .class.getClassLoader().getResourceAsStream取值

  • properties.load(inputStream);//IO流取值

  • 本質----------------獲取資料庫資料

POJO --- 提供一個實體,對物件的基本操作啊,set,get值

Dao --- 提供資料-怎麼提供?--依照你輸入的引數獲取想要的返回(返回物件需new物件)

Service --- 資料處理--怎麼處理?--引入dao,拿到dao的資料封裝一下(這麼做的意義?Controller直接拿dao不好嗎?)

作用:---實現本層資料共享(不同controller都可以呼叫Service)---1.獲取資料---2.對資料進行處理,如:判別,對資料進行計算

怎麼處理的? 通過入參啊,然後呼叫dao的進行處理啊。。。

  • 答:1.從引入dao來說,如果你直接由controller來進行,那麼DAO發生替換(比如從oracle遷移mysql),需要找到所有controller裡的呼叫點,逐一修改。
  • 2.如果每個判別,操作都由controller來進行,那麼同層的controller並不能互通(處理資料),比如:折扣計算,反作弊判定

Controller

  1. package com.zjz.dao;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.sql.*;
  5. import java.util.Properties;
  6. //操作資料庫的公共類
  7. public class BaseDao {
  8. private static String driver;
  9. private static String url;
  10. private static String username;
  11. private static String password;
  12. //靜態程式碼塊,類載入的時候就初始化
  13. static {
  14. Properties properties = new Properties();
  15. //通過類載入器讀取對應的資源
  16. InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
  17. try {
  18. properties.load(is);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. driver = properties.getProperty("driver");
  23. url = properties.getProperty("url");
  24. username = properties.getProperty("username");
  25. password = properties.getProperty("password");
  26. }
  27. //獲取資料的連線
  28. public static Connection getConnection(){
  29. Connection connection = null;
  30. try {
  31. Class.forName(driver);
  32. connection = DriverManager.getConnection(url,username,password);
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. return connection;
  37. }
  38. //編寫查詢公共類
  39. public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
  40. preparedStatement = connection.prepareStatement(sql);
  41. int len = params.length;
  42. for(int i = 0;i<len;i++){
  43. //setObject 佔位符從1開始,陣列是從0開始
  44. preparedStatement.setObject(i+1,params[i]);
  45. }
  46. resultSet = preparedStatement.executeQuery();
  47. return resultSet;
  48. }
  49. //編寫增刪改公共方法
  50. public static int execute(Connection connection,String sql,Object[] params, PreparedStatement preparedStatement) throws SQLException {
  51. preparedStatement = connection.prepareStatement(sql);
  52. int len = params.length;
  53. for(int i = 0;i<len;i++){
  54. //setObject 佔位符從1開始,陣列是從0開始
  55. preparedStatement.setObject(i+1,params[i]);
  56. }
  57. int updateRows = preparedStatement.executeUpdate();
  58. return updateRows;
  59. }
  60. //釋放資源
  61. public static boolean closeResource(Connection connection,ResultSet resultSet, PreparedStatement preparedStatement){
  62. boolean flag = true;
  63. if(resultSet!=null){
  64. try {
  65. resultSet.close();
  66. //GC回收
  67. resultSet = null;
  68. } catch (SQLException throwables) {
  69. throwables.printStackTrace();
  70. flag = false;
  71. }
  72. }
  73. if(connection!=null){
  74. try {
  75. connection.close();
  76. //GC回收
  77. connection = null;
  78. } catch (SQLException throwables) {
  79. throwables.printStackTrace();
  80. flag = false;
  81. }
  82. }
  83. if(preparedStatement!=null){
  84. try {
  85. preparedStatement.close();
  86. //GC回收
  87. preparedStatement = null;
  88. } catch (SQLException throwables) {
  89. throwables.printStackTrace();
  90. flag = false;
  91. }
  92. }
  93. return flag;
  94. }
  95. }
  • 8.編寫字元編碼過濾器

    • Filter類
    • web配置

功能一 登入功能的實現

編寫

  • 1.編寫前端
  • 2.設定首頁,web.xml
  1. <!--設定歡迎頁面-->
  2. <welcome-file-list>
  3. <welcome-file>/login.jsp</welcome-file>
  4. </welcome-file-list>
  • 3.編寫dao層,使用者登入的介面
  1. public interface UserDao {
  2. //得到要登入的使用者
  3. public User getLoginUser(Connection connection,String userCode) throws SQLException;
  4. }
  • 4.編寫dao介面實現類
  1. public class UserDaoImpl implements UserDao{
  2. public User getLoginUser(Connection connection, String userCode) throws SQLException {
  3. PreparedStatement pstm = null;
  4. ResultSet rs = null;
  5. User user = null;
  6. if(connection != null){
  7. String sql = "select * from smbms_user where userCode = ?";
  8. Object[] params = {userCode};
  9. rs = BaseDao.execute(connection, pstm, rs, sql, params);
  10. if(rs.next()){
  11. user = new User();
  12. user.setId(rs.getInt("id"));
  13. user.setUserCode(rs.getString("userCode"));
  14. user.setUserName(rs.getString("userName"));
  15. user.setUserPassword(rs.getString("userPassword"));
  16. user.setGender(rs.getInt("gender"));
  17. user.setBirthday(rs.getDate("birthday"));
  18. user.setPhone(rs.getString("phone"));
  19. user.setAddress(rs.getString("address"));
  20. user.setUserRole(rs.getInt("userRole"));
  21. user.setCreatedBy(rs.getInt("createdBy"));
  22. user.setCreationDate(rs.getTimestamp("creationDate"));
  23. user.setModifyBy(rs.getInt("modifyBy"));
  24. user.setModifyDate(rs.getTimestamp("modifyDate"));
  25. }
  26. BaseDao.closeResource(null,pstm,rs);
  27. }
  28. return user;
  29. }
  30. }
  • 5.業務層介面
    1. public interface UserService {
    2. //使用者登入
    3. public User login(String userCode, String password);
    4. }
  • 6.業務層實現類
  1. public class UserServiceImpl implements UserService{
  2. //業務層都會呼叫dao層,所以我們要引入dao層
  3. private UserDao userDao;
  4. public UserServiceImpl() {
  5. userDao = new UserDaoImpl();
  6. }
  7. public User login(String userCode, String password) {
  8. Connection connection = null;
  9. User user = null;
  10. try {
  11. connection = BaseDao.getConnection();
  12. //通過業務層呼叫具體的資料庫操作
  13. user = userDao.getLoginUser(connection,userCode);
  14. } catch (SQLException throwables) {
  15. throwables.printStackTrace();
  16. }finally {
  17. BaseDao.closeResource(connection,null,null);
  18. }
  19. return user;
  20. }
  21. @Test
  22. public void test(){
  23. UserServiceImpl userService = new UserServiceImpl();
  24. User wen = userService.login("wen", "123");
  25. System.out.println("密碼為:" + wen.getUserPassword());
  26. }
  27. }
  • 7.servlet層實現
  1. public class LoginServlet extends HttpServlet {
  2. //Servlet:控制層,呼叫業務層程式碼
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. System.out.println("LoginServlet---start");
  6. //獲取使用者的使用者名稱和密碼
  7. String userCode = req.getParameter("userCode");
  8. String userPassword = req.getParameter("userPassword");
  9. //和使用者資料庫中的密碼對比,呼叫業務層
  10. UserService userService = new UserServiceImpl();
  11. User user = userService.login(userCode, userPassword);//登入的人查出來
  12. if(user != null&&(user.getUserPassword().equals(userPassword))){//查到有這個人
  13. //將使用者的資訊放到session中
  14. req.getSession().setAttribute(Constants.USER_SESSION,user);
  15. //跳轉到主頁
  16. resp.sendRedirect("jsp/frame.jsp");
  17. }else {//查無此人
  18. //轉發回登入頁面,並提示錯誤
  19. req.setAttribute("error","使用者名稱,密碼不正確");
  20. req.getRequestDispatcher("login.jsp").forward(req,resp);
  21. }
  22. }
  23. @Override
  24. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  25. doGet(req, resp);
  26. }
  27. }
  • 8.註冊servle
  1. <servlet>
  2. <servlet-name>LoginServlet</servlet-name>
  3. <servlet-class>com.zjz.servlet.user.LoginServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>LoginServlet</servlet-name>
  7. <url-pattern>/login.do</url-pattern>
  8. </servlet-mapping>
  • 9.編寫過濾器,攔截沒登入的
  1. public class SysFilter implements Filter {
  2. public void init(FilterConfig filterConfig) throws ServletException {
  3. }
  4. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  5. HttpServletRequest request = (HttpServletRequest) servletRequest;
  6. HttpServletResponse response = (HttpServletResponse)servletResponse;
  7. //從session中獲取使用者
  8. User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
  9. if(user==null){//說明已經登出了
  10. response.sendRedirect("/error.jsp");
  11. }else {
  12. filterChain.doFilter(servletRequest,servletResponse);
  13. }
  14. }
  15. public void destroy() {
  16. }
  17. }
  1. <!--使用者登入過濾器-->
  2. <filter>
  3. <filter-name>SysFilter</filter-name>
  4. <filter-class>com.zjz.Filter.SysFilter</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>SysFilter</filter-name>
  8. <url-pattern>/jsp/*</url-pattern>
  9. </filter-mapping>
  • 10.由底層向上層寫

功能二,修改密碼-修當前的

修改所有的,還是修改當前的---兩個可以呼叫同一個DAO(修改),但業務就不一樣了吧,修當前的id需要通過session獲取吧。

編寫

  • 設定文字型別

    resp.setContentType("application/json"); // setContentType 設定文字的型別

功能三,使用者介面

編寫

看到的頁面顯示多少條,當前頁碼,都得與當前的使用者list繫結

每次點選切換的時候也就是再次執行SQL進行分頁的處理,並不是同一批資料分割開。。。(可利用前端進行分割--)

所以總數量的獲取需要單獨寫一個SQL

總數量的作用就是,幫助我們顯示有幾頁

跳轉由前端獲取頁數,或者上一頁,下一頁由前端引數直接控制

  • 總體思路,使用者展示

    • List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
    • 總數量--返回一個總數量
    • 分頁Bean 專用於分頁。。也就是一個服務類,利用總數量服務currentPageNo動態變化

  • 1.匯入分頁的工具類

  • 2.使用者列表的匯入

    • userlist.jsp
  • 1.獲取使用者數量

    • UserDao UserDaoImpl UserService UserServiceImpl
  • 2.分頁的邏輯

    • 在資料庫中分頁使用 Limit startIndex,pageSize; 總數
    • 0,5--第1頁-- 6,5--第2頁-- 11,5--第3頁----每頁五個
    • 當前頁 (當前頁-1) * 頁面大小
  • 3.獲取使用者列表

    • userdao

    1. public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize)throws Exception;
    • userdaoImpl UserService UserServiceImpl
  • 4.使用者顯示的servlet

    • 1.獲取使用者前端的資料(查詢)
    • 2.判斷請求是否需要執行,看引數的值判斷
    • 3.為了實現分頁,需要計算當前頁面的總頁面,以及頁面大小
    • 4.使用者前端展示
    • 5.返回前端
  1. -------- 更多學習 https://zhangjzm.gitee.io/self_study