Springmvc框架-实现用户列表查询·

需求:通过用户名和用户角色查询符合条件的用户列表信息

UserController.java

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package cn.smbms.controller;
import java.util.List;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
 
@Controller
@RequestMapping("/user")
public class UserController{
    private Logger logger = Logger.getLogger(UserController.class);
     
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
     
    @RequestMapping(value="/login.html")
    public String login(){
        logger.debug("UserController welcome SMBMS==================");
        return "login";
    }
     
    @RequestMapping(value="/dologin.html",method=RequestMethod.POST)
    public String doLogin(@RequestParam String userCode,@RequestParam String userPassword,HttpServletRequest request,HttpSession session){
        logger.debug("doLogin====================================");
        //调用service方法,进行用户匹配
        User user = userService.login(userCode,userPassword);
        if(null != user){//登录成功
            //放入session
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转(frame.jsp)
            return "redirect:/user/main.html";
            //response.sendRedirect("jsp/frame.jsp");
        }else{
            //页面跳转(login.jsp)带出提示信息--转发
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }
    @RequestMapping(value="/main.html")
    public String main(HttpSession session){
        if(session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/login.html";
        }
        return "frame";
    }
     
    @RequestMapping(value="/logout.html")
    public String logout(HttpSession session){
        //清除session
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }
    @RequestMapping(value="/exlogin.html",method=RequestMethod.GET)
    public String exLogin(@RequestParam String userCode,@RequestParam String
 
userPassword){
        logger.debug("exLogin====================================");
        //调用service方法,进行用户匹配
        User user = userService.login(userCode,userPassword);
        if(null == user){//登录失败
            throw new RuntimeException("用户名或者密码不正确!");
        }
        return "redirect:/user/main.html";
    }
     
    /*@ExceptionHandler(value={RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("e", e);
        return "error";
    }*/
     
    @RequestMapping(value="/userlist.html")
    public String getUserList(Model model,
                            @RequestParam(value="queryname",required=false) String queryUserName,
                            @RequestParam(value="queryUserRole",required=false) String queryUserRole,
                            @RequestParam(value="pageIndex",required=false) String pageIndex){
        logger.info("getUserList ---- > queryUserName: " + queryUserName);
        logger.info("getUserList ---- > queryUserRole: " + queryUserRole);
        logger.info("getUserList ---- > pageIndex: " + pageIndex);
        int _queryUserRole = 0;    
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
     
        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
         
        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/user/syserror.html";
                //response.sendRedirect("syserror.jsp");
            }
        }  
        //总数量(表)   
        int totalCount  = userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }
     
    @RequestMapping(value="/syserror.html")
    public String sysError(){
        return "syserror";
    }
     
     
     
}

  RoleDao.java

1
2
3
4
5
6
7
8
9
10
11
package cn.smbms.dao.role;
 
import java.sql.Connection;
import java.util.List;
import cn.smbms.pojo.Role;
 
public interface RoleDao {
     
    public List<Role> getRoleList(Connection connection)throws Exception;
 
}

  RoleDaoImpl.java

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
package cn.smbms.dao.role;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.smbms.dao.BaseDao;
import cn.smbms.pojo.Role;
 
@Repository
public class RoleDaoImpl implements RoleDao{
 
    @Override
    public List<Role> getRoleList(Connection connection) throws Exception {
        // TODO Auto-generated method stub
        PreparedStatement pstm = 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, pstm, 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, pstm, rs);
        }
         
        return roleList;
    }
 
}

  RoleService.java

1
2
3
4
5
6
7
8
9
10
11
package cn.smbms.service.role;
 
import java.util.List;
 
import cn.smbms.pojo.Role;
 
public interface RoleService {
     
    public List<Role> getRoleList();
     
}

  RoleServiceImpl.java

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
package cn.smbms.service.role;
 
import java.sql.Connection;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.smbms.dao.BaseDao;
import cn.smbms.dao.role.RoleDao;
import cn.smbms.pojo.Role;
 
@Service
public class RoleServiceImpl implements RoleService{
    @Resource
    private RoleDao roleDao;
     
    @Override
    public List<Role> getRoleList() {
        // TODO Auto-generated method stub
        Connection connection = null;
        List<Role> roleList = null;
        try {
            connection = BaseDao.getConnection();
            roleList = roleDao.getRoleList(connection);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            BaseDao.closeResource(connection, null, null);
        }
        return roleList;
    }
     
}

  添加工具类PageSurport.java

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
package cn.smbms.tools;
 
public class PageSupport {
    //当前页码-来自于用户输入
    private int currentPageNo = 1;
     
    //总数量(表)
    private int totalCount = 0;
     
    //页面容量
    private int pageSize = 0;
     
    //总页数-totalCount/pageSize(+1)
    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;
        }
    }
     
}

  syserror.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>请登录后再访问该页面!</h1>
<a href="${pageContext.request.contextPath }/user/login.html">返回</a>
</body>
</html>

  rolepage.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
     
</script>
</head>
<body>
        <div class="page-bar">
            <ul class="page-num-ul clearfix">
                <li>共${param.totalCount }条记录   ${param.currentPageNo }/${param.totalPageCount }页</li>
                <c:if test="${param.currentPageNo > 1}">
                    <a href="javascript:page_nav(document.forms[0],1);">首页</a>
                    <a href="javascript:page_nav(document.forms[0],${param.currentPageNo-1});">上一页</a>
                </c:if>
                <c:if test="${param.currentPageNo < param.totalPageCount }">
                    <a href="javascript:page_nav(document.forms[0],${param.currentPageNo+1 });">下一页</a>
                    <a href="javascript:page_nav(document.forms[0],${param.totalPageCount });">最后一页</a>
                </c:if>
                   
            </ul>
         <span class="page-go-form"><label>跳转至</label>
         <input type="text" name="inputPage" id="inputPage" class="page-key" />页
         <button type="button" class="page-btn" onClick='jump_to(document.forms[0],document.getElementById("inputPage").value)'>GO</button>
        </span>
        </div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/rollpage.js"></script>
</html>

  userList.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/head.jsp"%>
        <div class="right">
            <div class="location">
                <strong>你现在所在的位置是:</strong>
                <span>用户管理页面</span>
            </div>
            <div class="search">
                <form method="post" action="${pageContext.request.contextPath }/user/userlist.html">
                    <input name="method" value="query" class="input-text" type="hidden">
                     <span>用户名:</span>
                     <input name="queryname" class="input-text"  type="text" value="${queryUserName }">
                      
                     <span>用户角色:</span>
                     <select name="queryUserRole">
                        <c:if test="${roleList != null }">
                           <option value="0">--请选择--</option>
                           <c:forEach var="role" items="${roleList}">
                                <option <c:if test="${role.id == queryUserRole }">selected="selected"</c:if>
                                value="${role.id}">${role.roleName}</option>
                           </c:forEach>
                        </c:if>
                    </select>
                      
                     <input type="hidden" name="pageIndex" value="1"/>
                     <input  value="查 询" type="submit" id="searchbutton">
                     <a href="${pageContext.request.contextPath}/jsp/useradd.jsp" >添加用户</a>
                </form>
            </div>
            <!--用户-->
            <table class="providerTable" cellpadding="0" cellspacing="0">
                <tr class="firstTr">
                    <th width="10%">用户编码</th>
                    <th width="20%">用户名称</th>
                    <th width="10%">性别</th>
                    <th width="10%">年龄</th>
                    <th width="10%">电话</th>
                    <th width="10%">用户角色</th>
                    <th width="30%">操作</th>
                </tr>
                   <c:forEach var="user" items="${userList }" varStatus="status">
                    <tr>
                        <td>
                        <span>${user.userCode }</span>
                        </td>
                        <td>
                        <span>${user.userName }</span>
                        </td>
                        <td>
                            <span>
                                <c:if test="${user.gender==1}">男</c:if>
                                <c:if test="${user.gender==2}">女</c:if>
                            </span>
                        </td>
                        <td>
                        <span>${user.age}</span>
                        </td>
                        <td>
                        <span>${user.phone}</span>
                        </td>
                        <td>
                            <span>${user.userRoleName}</span>
                        </td>
                        <td>
                        <span><a class="viewUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/statics/images/read.png" alt="查看" title="查看"/></a></span>
                        <span><a class="modifyUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/statics/images/xiugai.png" alt="修改" title="修改"/></a></span>
                        <span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/statics/images/schu.png" alt="删除" title="删除"/></a></span>
                        </td>
                    </tr>
                </c:forEach>
            </table>
            <input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
            <c:import url="rollpage.jsp">
                <c:param name="totalCount" value="${totalCount}"/>
                <c:param name="currentPageNo" value="${currentPageNo}"/>
                <c:param name="totalPageCount" value="${totalPageCount}"/>
            </c:import>
        </div>
    </section>
 
<!--点击删除按钮后弹出的页面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
    <div class="removerChid">
        <h2>提示</h2>
        <div class="removeMain">
            <p>你确定要删除该用户吗?</p>
            <a href="#" id="yes">确定</a>
            <a href="#" id="no">取消</a>
        </div>
    </div>
</div>
 
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/userlist.js"></script>

 运行结果:

 

 

posted on   ~码铃薯~  阅读(1122)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示