0%

JavaWeb实战--Smbms项目

整体框架

image-20210225212626877

数据库表

image-20210225212812090

项目如何搭建?通过Maven模板创建项目

项目搭建步骤

  1. 通过Maven模板搭建项目

  2. 配置Tomcat

  3. 导包(测试项目是否顺利运行)

    1
    servlet-api,jsp-api,jstl,standard,mysql-connector-java等
  4. 创建项目包结构

    image-20210225231854758

  5. 编写实体类(ORM映射)

    对应数据表中的所有变量,再加上get&set方法

    image-20210225225015070

  6. 编写基础公共类

    • 数据库配置文件

      1
      2
      3
      4
      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
      username=root
      password=123456
    • 编写数据库公共类BaseDao

      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
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
       package com.lan5th.dao;

      import java.io.InputStream;
      import java.sql.*;
      import java.util.Properties;

      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 in = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");

      try {
      properties.load(in);
      } catch (Exception 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++){
      preparedStatement.setObject(i+1,params[i]);
      }

      resultSet = preparedStatement.executeQuery();
      //返回结果集resultSet
      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++){
      preparedStatement.setObject(i+1,params[i]);
      }

      int updateRows = preparedStatement.executeUpdate();
      //返回受影响的行数
      return updateRows;
      }

      //回收资源
      public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
      boolean flag = true;

      if (resultSet != null){
      try {
      resultSet.close();
      resultSet = null;
      } catch (SQLException throwables) {
      throwables.printStackTrace();
      flag = false;
      }
      try {
      preparedStatement.close();
      preparedStatement = null;
      } catch (SQLException throwables) {
      throwables.printStackTrace();
      flag = false;

      }
      try {
      connection.close();
      connection = null;
      } catch (SQLException throwables) {
      throwables.printStackTrace();
      flag = false;

      }
      }

      return flag;
      }
      }
    • 编写字符编码过滤器

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      package com.lan5th.filter;

      import javax.servlet.*;
      import java.io.IOException;

      public class CharacterEncodingFilter implements Filter {
      public void init(FilterConfig filterConfig) throws ServletException {
      }

      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      servletRequest.setCharacterEncoding("utf-8");
      servletResponse.setCharacterEncoding("utf-8");
      servletResponse.setContentType("text/html;charset=utf-8");

      filterChain.doFilter(servletRequest,servletResponse);
      }

      public void destroy() {
      }
      }
  7. 导入静态资源

创建数据表

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
CREATE TABLE `smbms_address` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`contact` varchar(15) DEFAULT NULL COMMENT '联系人姓名',
`addressDesc` varchar(50) DEFAULT NULL COMMENT '收货地址',
`postCode` varchar(15) DEFAULT NULL COMMENT '邮编',
`tel` int(20) DEFAULT NULL COMMENT '联系人电话',
`createdBy` varchar(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '修改者',
`modifyDate` datetime DEFAULT NULL COMMENT '修改时间',
`userId` bigint(20) DEFAULT NULL COMMENT '用户ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `smbms_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`userCode` varchar(15) DEFAULT NULL COMMENT '用户编码',
`userName` varchar(15) DEFAULT NULL COMMENT '用户名字',
`userPassword` varchar(20) DEFAULT NULL COMMENT '用户密码',
`gender` int(10) DEFAULT NULL COMMENT '性别',
`birthday` date DEFAULT NULL COMMENT '出生日期',
`phone` varchar(20) DEFAULT NULL COMMENT '电话',
`address` varchar(30) DEFAULT NULL COMMENT '地址',
`userRole` bigint(20) DEFAULT NULL COMMENT '用户角色',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `smbms_bill` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`billCode` varchar(30) DEFAULT NULL COMMENT '账单编码',
`productName` varchar(20) DEFAULT NULL COMMENT '商品名称',
`productDesc` varchar(50) DEFAULT NULL COMMENT '商品描述',
`productUnit` varchar(60) DEFAULT NULL COMMENT '商品数量',
`productCount` decimal(20,2) DEFAULT NULL COMMENT '总金额',
`totalPrice` decimal(20,2) DEFAULT NULL COMMENT '是否支付',
`isPayment` int(10) DEFAULT NULL COMMENT '供应商ID',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `smbms_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`roleCode` varchar(30) DEFAULT NULL COMMENT '角色编码',
`roleName` varchar(15) DEFAULT NULL COMMENT '角色名称',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `smbms_provider` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`proCode` varchar(15) DEFAULT NULL COMMENT '供应商编码',
`proName` varchar(15) DEFAULT NULL COMMENT '供应商名称',
`proDesc` varchar(50) DEFAULT NULL COMMENT '供应商描述',
`proContact` varchar(15) DEFAULT NULL COMMENT '供应商联系人',
`proPhone` varchar(20) DEFAULT NULL COMMENT '供应商电话',
`userAddress` varchar(30) DEFAULT NULL COMMENT '供应商地址',
`userFax` varchar(20) DEFAULT NULL COMMENT '供应商传真',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

登录过程实现

image-20210226104128466

  1. 编写前端页面

  2. 设置首页

    1
    2
    3
    4
    <!--设置欢迎页-->
    <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
  3. 编写dao层用户登陆的接口UserDao

    1
    2
    3
    public interface UserDao {
    public User getLoginUser(Connection connection,String userCode);
    }l
  4. 编写dao接口实现类UserDaoImpl

    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
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    public class UserDaoImpl implements UserDao {
    public User getLoginUser(Connection connection, String userCode) {
    PreparedStatement ppst = null;
    ResultSet rs = null;
    User user = null;

    if (connection!=null){
    //编写sql
    String sql = "select * from smbms_user where userCode=?";
    Object[] params = {userCode};
    R
    try {
    //公共类BaseDao的execute方法返回ResultSet对象
    rs = BaseDao.execute(connection, ppst, 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.getDate("creationDate"));
    user.setModifyBy(rs.getInt("modifyBy"));
    user.setModifyDate(rs.getTimestamp("modifyDate"));
    }
    BaseDao.closeResource(null,ppst,rs);
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    return user;
    }
    }
  5. 业务层接口UserService

    1
    2
    3
    public interface UserService {
    public User login(String userCode, String password);
    }
  6. 业务层实现类UserServiceImpl

    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
    26
    27
    28
    29
    30
    31
    32
    33
    public class UserServiceImpl implements UserService {
    private UserDao 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 (Exception e) {
    return null;
    } finally {
    BaseDao.closeResource(connection, null, null);
    }
    //若不为空,则检查用户码和密码是否相匹配
    if (user!=null){
    if (user.getUserCode().equals(userCode)) {
    if (user.getUserPassword().equals(password)) {
    return user;
    }
    }
    }
    //为空则直接返回null
    return null;
    }
    }
  7. 编写servlet层LoginServlet

    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
    26
    27
    public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String userCode = req.getParameter("userCode");
    String userPassword = req.getParameter("userPassword");

    //由业务层进行用户名和密码比对
    UserServiceImpl userService = new UserServiceImpl();
    User user = userService.login(userCode, userPassword);

    if (user!=null){
    //跳转主页,生成session
    req.getSession().setAttribute(Constants.USER_SESSION,user);
    req.getRequestDispatcher("jsp/userPage.jsp").forward(req, resp);
    }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);
    }
    }
  8. 注册servlet

    1
    2
    3
    4
    5
    6
    7
    8
    <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.lan5th.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
  9. 测试访问,确保以上功能成功

登录功能优化

  • 注销功能:编写LogoutServlet移除Session

    1
    req.getSession().removeAttribute(Constants.USER_SESSION);
  • 登录拦截器:过滤器

    • 编写过滤器

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      public class SysFilter implements Filter {
      public void init(FilterConfig filterConfig) throws ServletException {

      }

      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
      HttpServletResponse response = (HttpServletResponse) servletResponse;

      User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

      if(user == null){
      response.sendRedirect(request.getContextPath()+"/login.jsp");
      }else {
      filterChain.doFilter(request,response);
      }
      }

      public void destroy() {

      }
      }
    • 注册过滤器

修改密码功能实现

  1. 编写页面

  2. 扩充UserDao接口

    1
    public int pwdModify(Connection connection, int userCode, String pwd);
  3. 扩充UserDao实现类UserDaoImpl

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public int pwdModify(Connection connection, int id, String pwd) {
    PreparedStatement ppst = null;
    User user = null;
    int flag = 0;

    if (connection!=null){
    String sql = "update smbms_user set userPassword=? where id=?";
    Object[] params = {pwd,id};

    try {
    flag = BaseDao.execute(connection, ppst, sql, params);
    BaseDao.closeResource(null,ppst,null);
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    return flag;
    }
  4. 扩充UserService接口

    1
    public boolean pwdModify(int id, String password);
  5. 扩充UserService实现类UserServiceImpl

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public boolean pwdModify(int id, String password) {
    Connection connection = null;
    boolean flag = false;

    //修改密码
    try {
    connection = BaseDao.getConnection();
    if (userDao.pwdModify(connection, id, password) > 0) {
    flag = true;
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    BaseDao.closeResource(connection, null, null);
    }

    return flag;
    }
  6. 实现Userservlet复用

    通过前端传入method属性值来判断执行的方法

    1
    2
    3
    <form method="post" action="${pageContext.request.contextPath}/user.do">
    <input type="hidden" name="method" value="modifyPwd">
    </form>
    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
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getParameter("method");
    if (method.equals("modifyPwd")&&method!=null){
    this.modifyPwd(req,resp);
    }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
    }

    protected boolean modifyPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Object o = req.getSession().getAttribute(Constants.USER_SESSION);
    String newPassword = req.getParameter("newPassword");
    boolean flag = false;

    if (o!=null&& !StringUtils.isNullOrEmpty(newPassword)){
    UserServiceImpl userService = new UserServiceImpl();
    flag = userService.pwdModify(((User) o).getId(), newPassword);
    if (flag){
    req.setAttribute("message", "密码修改成功");
    //密码修改成功,移除Session
    req.getSession().removeAttribute(Constants.USER_SESSION);
    req.getRequestDispatcher("/error.jsp").forward(req,resp);
    return flag;
    }
    }
    req.setAttribute("message", "密码修改失败,请检查输入");
    req.getRequestDispatcher("/jsp/pwdModify.jsp").forward(req,resp);

    return flag;
    }
    }
  7. 利用ajax实现动态请求

    image-20210227223504709

  8. 在UserServlet中实现动态请求的响应

    image-20210227223715327

    image-20210227223814004

用户管理功能

因完成该功能需要前端js支持,暂时不给予实现,只给出关键代码

image-20210228094054117

  1. 添加分页支持PageSupport

    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
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    public class PageSupport {
    private int currentPageNo = 1;
    private int totalCount = 0;
    private int pageSize = 0;
    private int totalPageCount = 1;

    public int getCurrentPageNo() {
    return currentPageNo;
    }

    public void setCurrentPageNo(int currentPageNo) {
    if (currentPageNo > 0){
    this.currentPageNo = currentPageNo;
    }
    }

    public int getTotalCount() {
    return totalCount;
    }

    public void setTotalCount(int totalCount) {
    if(totalCount > 0){
    this.totalCount = totalCount;
    this.setTotalPageCountByRs();
    }
    }

    public int getPageSize() {
    return pageSize;
    }

    public void setPageSize(int pageSize) {
    if (pageSize > 0){
    this.pageSize = pageSize;
    }
    }

    public int getTotalPageCount() {
    return totalPageCount;
    }

    public void setTotalPageCount(int totalPageCount) {
    this.totalPageCount = totalPageCount;
    }

    public void setTotalPageCountByRs(){
    if (this.totalCount % this.pageSize == 0){
    this.totalPageCount = this.totalCount / this.pageSize;
    }else if (this.totalCount % this.pageSize > 0){
    this.totalPageCount = this.totalCount % this.pageSize + 1;
    }else {
    this.totalPageCount = 0;
    }
    }
    }
  2. 扩充UserDaoImpl层

    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
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    //获取展示的数据条数
    public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
    PreparedStatement ppst = null;
    ResultSet rs = null;
    int count = 0;

    if (connection!=null){
    StringBuffer sql = new StringBuffer();
    sql.append("select count(1) from smbms_user u,smbms_role r where u.userRole = r.id");
    ArrayList list = new ArrayList();
    //选择用户名添加限制条件
    if (!StringUtils.isNullOrEmpty(username)){
    sql.append(" and u.username like ?");
    //模糊查询前后加百分号
    list.add("%"+username+"%");
    }
    //选择用户角色添加限制条件
    if (userRole>0){
    sql.append(" and u.userRole = ?");
    list.add(userRole);
    }
    //将list转换为数组
    Object[] params = list.toArray();
    BaseDao.execute(connection,ppst,sql.toString(),params);

    if (rs.next()){
    count = rs.getInt("count");
    }
    }
    return count;
    }

    //获取用户列表
    public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException {
    PreparedStatement ppst = null;
    ResultSet rs = null;
    List<User> userList = new ArrayList<User>();

    if (connection!=null){
    StringBuffer sql = new StringBuffer();
    sql.append("select count(1) from smbms_user u,smbms_role r where u.userRole = r.id");
    ArrayList list = new ArrayList();
    //选择用户名添加限制条件
    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查询的limit实现分页
    sql.append(" order by creationDate DESC limit ?,?");
    currentPageNo = (currentPageNo-1)*pageSize;
    list.add(currentPageNo);
    list.add(pageSize);

    //将list转换为数组
    Object[] params = list.toArray();
    rs = BaseDao.execute(connection,ppst,rs,sql.toString(),params);

    while (rs.next()){
    User user = new User();
    user.setId(rs.getInt("id"));
    user.setUserCode(rs.getString("userCode"));
    user.setUserName(rs.getString("userName"));
    user.setGender(rs.getInt("gender"));
    user.setBirthday(rs.getDate("birthday"));
    user.setPhone(rs.getString("phone"));
    user.setUserRole(rs.getInt("userRole"));
    userList.add(user);
    }
    BaseDao.closeResource(null,ppst,rs);
    }
    return userList;
    }
  3. 扩充UserServiceImpl层

    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
    26
    27
    public int getUserCount(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;
    }

    public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize) {
    Connection connection = null;
    List<User> userList = null;
    try{
    connection = BaseDao.getConnection();
    userList = userDao.getUserList(connection, username, userRole, currentPageNo,pageSize);
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    } finally {
    BaseDao.closeResource(connection,null,null);
    }
    return userList;
    }
  4. 编写RoleDaoImpl层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    public class RoleDaoImpl implements RoleDao{
    public List<Role> getRoleList(Connection connection) throws SQLException {
    PreparedStatement ppst = null;
    ResultSet rs = null;
    ArrayList<Role> roleList = new ArrayList<Role>();

    if(connection!= null){
    String sql = "select * from smbms_role";
    Object[] params = {};
    rs = BaseDao.execute(connection,ppst,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,ppst,rs);
    }
    return roleList;
    }
    }
  5. 编写RoleServiceImpl层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    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;
    }
    }
  6. 扩充UserServlet(重点)

    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
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    protected void query(HttpServletRequest req, HttpServletResponse resp){
    //获取前端数据
    String queryUserName = req.getParameter("queryName");
    String temp = req.getParameter("queryUserRole");
    String pageIndex = req.getParameter("pageIndex");
    int queryUserRole = 0;

    //获取用户列表
    UserServiceImpl userService = new UserServiceImpl();

    int pageSize = 5;
    int currentPageNo = 1;

    if (queryUserName == null){
    queryUserName="";
    }
    if (temp != null&&!temp.equals("")){
    //字符串转int
    queryUserRole = Integer.parseInt(temp);
    }
    if (queryUserName == null){
    currentPageNo = Integer.parseInt(pageIndex);
    }

    int totalCount = userService.getUserCount(queryUserName, queryUserRole);

    PageSupport pageSupport = new PageSupport();
    pageSupport.setCurrentPageNo(currentPageNo);
    pageSupport.setPageSize(pageSize);
    pageSupport.setTotalCount(totalCount);

    int totalPageCount = pageSupport.getTotalCount();

    if (currentPageNo<1){
    currentPageNo = 1;
    }else if (currentPageNo>totalPageCount){
    currentPageNo=totalPageCount;
    }

    List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
    req.setAttribute("userList",userList);

    RoleServiceImpl roleService = new RoleServiceImpl();
    List<Role> roleList = roleService.getRoleList();
    req.setAttribute("roleList",roleList);
    req.setAttribute("totalCount",totalCount);
    req.setAttribute("currentPageNo",currentPageNo);

    try{
    req.getRequestDispatcher("userList.jsp").forward(req,resp);
    } catch (ServletException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

供应商管理,订单管理等功能实现与用户管理类似,不再重复给出类似代码,读者可自己增加相应练习,巩固基础。

本篇JavaWeb实战到此完结