使用Maven
搭配一个maven web项目
配置Tomcat
测试项目是否能够跑起来
导入项目中会遇到的jar包
jsp,servlet,mysql驱动,jstl,standard…
编写公共基础类
(1)数据库配置文件(放在resources目录下的db.resources文件)
(2)编写数据库公共类
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} 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,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始
preparedStatement.setObject(i+1,params);
}
//此处不需要再传入sql参数,已经预编译
resultSet = preparedStatement.executeQuery();
return resultSet;
}
//编写增删改的公共方法
public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始
preparedStatement.setObject(i+1,params);
}
//此处不需要再传入sql参数,已经预编译
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();
//GC回收,防止关闭后仍不为null
resultSet=null;
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
//GC回收,防止关闭后仍不为null
preparedStatement=null;
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}
}
if(connection!=null){
try {
connection.close();
//GC回收,防止关闭后仍不为null
connection=null;
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}
}
return flag;
}
}
(3)编写字符编码过滤器(编写完后记得在web.xml中进行过滤器注册)
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf8");
servletResponse.setCharacterEncoding("utf8");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>系统登录 - 超市订单管理系统title>
<%--注意这里css路径href使用绝对路径,否则加载不出来css页面--%>
<link type="text/css" rel="stylesheet" href="css/style.css" />
<script type="text/javascript">
/* if(top.location!=self.location){
top.location=self.location;
} */
script>
head>
<body class="login_bg">
<section class="loginBox">
<header class="loginHeader">
<h1>超市订单管理系统h1>
header>
<section class="loginCont">
<form class="loginForm" action="${pageContext.request.contextPath}/login.do" name="actionForm" id="actionForm" method="post" >
<div class="info">${error }div>
<div class="inputbox">
<label for="userCode">用户名:label>
<input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
div>
<div class="inputbox">
<label for="userPassword">密码:label>
<input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
div>
<div class="subBtn">
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
div>
form>
section>
section>
body>
html>
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
//面向接口编程
public interface UserDao {
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
}
public class UserDaoImpl extends HttpServlet implements UserDao{
@Override
public User getLoginUser(Connection connection, String userCode) throws SQLException {
PreparedStatement pstm=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, sql, params, rs, pstm);
if (rs.next()){
user = new User();
user.setId(rs.getLong("id"));
user.setUserCode(rs.getString("userCode"));
user.setUserName(rs.getString("userName"));
user.setUserPassword(rs.getString("userPassword"));
user.setGender(rs.getInt("gender"));
//getDate只返回日期即哪一天;getTime只返回具体时间;getTimestamp返回日期和时间
user.setBirthday(rs.getDate("birthday"));
user.setPhone(rs.getString("phone"));
user.setAddress(rs.getString("address"));
user.setUserRole(rs.getLong("userRole"));
user.setCreatedBy(rs.getLong("createdBy"));
user.setCreationDate(rs.getTimestamp("creationDate"));
user.setModifyBy(rs.getLong("modifyBy"));
user.setModifyDate(rs.getTimestamp("modifyDate"));
}
//connection先不用关,可能存在业务
BaseDao.closeResource(null,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();
}
@Override
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;
}
@Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
//只查询userCode,只要数据库中有该用户编码即返回用户密码,没有验证password的正确性
User admin = userService.login("admin", "1234567");
System.out.println(admin.getUserPassword());
}
}
public class LoginServlet extends HttpServlet {
//Servlet:控制层,调用业务层代码
@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");
//和数据库中的密码进行对比,调用业务层
UserServiceImpl userService = new UserServiceImpl();
//这里已经把登录的人给查出来了
User user = userService.login(userCode, userPassword);
System.out.println();
//查有此人可以登录
if(user!=null){
if(user.getUserPassword().equals(userPassword)) {
//将用户信息放在session中
req.getSession().setAttribute(Constants.USER_SESSION, user);
//跳转到主页
resp.sendRedirect("jsp/frame.jsp");
}
else{
//转发回登录页面,提示用户名或密码错误
req.setAttribute("error","用户名或密码错误");
req.getRequestDispatcher("login.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);
}
}
注销:移除session,返回登录界面
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);
}
}
登录注销注册
<servlet>
<servlet-name>LoginServletservlet-name>
<servlet-class>com.zhemowang.servlet.user.LoginServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/login.dourl-pattern>
servlet-mapping>
<servlet>
<servlet-name>LoginoutServletservlet-name>
<servlet-class>com.zhemowang.servlet.user.LoginoutServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginoutServletservlet-name>
<url-pattern>/jsp/loginout.dourl-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、HttpServletResponse才能获取和利用session
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() {
}
}
登录拦截注册
<filter>
<filter-name>SysFilterfilter-name>
<filter-class>com.zhemowang.filter.SysFilterfilter-class>
filter>
<filter-mapping>
<filter-name>SysFilterfilter-name>
<url-pattern>/jsp/*url-pattern>
filter-mapping>
最后确保测试、登录、注销、权限都执行成功!
<li><a href="${pageContext.request.contextPath}/jsp/pwdmodify.jsp">密码修改a>li>
public interface UserDao {
//修改当前用户密码
public int updatePwd(Connection connection,int id,String password) throws SQLException;
}
public class UserDaoImpl extends HttpServlet implements UserDao{
@Override
//修改当前用户密码
public int updatePwd(Connection connection, int id, String password) throws SQLException {
//下面输出正确证明sql语句可能写错
System.out.println("UserDaoImpl"+id+":"+password);
PreparedStatement pstm=null;
int execute=0;
if(connection!=null){
String sql="update smbms_user set userPassword = ? where id= ?";
//特别注意password与id前后顺序,因为与sql语句有关
Object[] params={
password,id};
execute = BaseDao.execute(connection, sql, params,pstm);
BaseDao.closeResource(null,pstm,null);
}
return execute;
}
}
public interface UserService {
//根据用户Id修改密码
public boolean updatePwd(Integer id, String password) ;
}
public class UserServiceImpl implements UserService{
//业务层都会调用dao层,所以要引入dao层
private UserDao userDao;
public UserServiceImpl(){
userDao = new UserDaoImpl();
}
@Override
public boolean updatePwd(Integer id, String password) {
System.out.println("UserServiceImpl"+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;
}
@Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
boolean b = userService.updatePwd(1,"12345678");
System.out.println(b);
}
}
//实现servlet复用
public class UserServlet extends HttpServlet {
@Override
//调用updatePwd方法实现复用
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//可以用来验证前端隐藏信息是否正确
String method = req.getParameter("method");
if (method!=null&&method.equals("savepwd")){
this.updatePwd(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
//将该方法从doGet中提出来实现复用
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
//从session里拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
System.out.println("UserServlet"+newpassword);
boolean flag=false;
//注意StringUtils.isNullOrEmpty()如果为0或空返回true,所以取反才对;可以用
//newpassword!=null &&newpassword.length()!=0代替
if (o!=null && !(StringUtils.isNullOrEmpty(newpassword))){
UserServiceImpl userService = new UserServiceImpl();
flag=userService.updatePwd(((User)o).getId(),newpassword);
if(flag){
req.setAttribute("message","修改密码成功,请退出使用新密码登录");
//密码修改成功移除当前session(SysFilter自动判断session为空返回登录页面)
req.getSession().removeAttribute(Constants.USER_SESSION);
}else{
req.setAttribute("message","密码修改失败");
}
}else{
req.setAttribute("message","新密码有问题");
}
try {
req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
问题总结:
1. 前端图片路径问题:同一级目录下不能访问,必须…/回到上一级目录再访问同级目录下文件
2. s符号未发现问题:在前端文件head.jsp中没有发现多了这个文本删除线设置,导致网页默认文本带删除线;
总结:不是自己写的前端问题太多
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
public class UserServlet extends HttpServlet {
@Override
//调用updatePwd方法实现复用
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if (method!=null&&method.equals("savepwd")){
this.updatePwd(req,resp);
}else if (method!=null&&method.equals("pwdmodify")){
this.pwdmodify(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
//将该修改密码方法从doGet中提出来实现复用
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
//从session里拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
System.out.println("UserServlet"+newpassword);
boolean flag=false;
//注意StringUtils.isNullOrEmpty()如果为0或空返回true,所以取反才对;可以用
//newpassword!=null &&newpassword.length()!=0代替
if (o!=null && !(StringUtils.isNullOrEmpty(newpassword))){
UserServiceImpl userService = new UserServiceImpl();
flag=userService.updatePwd(((User)o).getId(),newpassword);
if(flag){
req.setAttribute("message","修改密码成功,请退出使用新密码登录");
//密码修改成功移除当前session(SysFilter自动判断session为空返回登录页面)
req.getSession().removeAttribute(Constants.USER_SESSION);
}else{
req.setAttribute("message","密码修改失败");
}
}else{
req.setAttribute("message","新密码有问题");
}
try {
req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//验证旧密码,session中存有用户旧密码,不需要再重新访问数据库
public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
//从session里拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
//万能的map:使用map存储返回前端的结果集
Map<String, String> resultMap = new HashMap<String, String>();
if(o==null){
//session过期或失效
resultMap.put("result","sessionerror");
}else if (StringUtils.isNullOrEmpty(oldpassword)){
//输入密码为空
resultMap.put("result","error");
}else{
String userPassword = ((User) o).getUserPassword();
if (userPassword.equals(oldpassword)){
//输入密码正确
resultMap.put("result","true");
}else {
//输入密码错误
resultMap.put("result","false");
}
}
try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
//JSONArray:阿里巴巴json转换格式工具类
/*resultMap={result=true,result=false}
json={"key":"value"}
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSP不支持绝对路径
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;
}
}
}
public interface UserDao {
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
//修改当前用户密码
public int updatePwd(Connection connection,int id,String password) throws SQLException;
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
}
@Override
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
PreparedStatement pstm=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<>();
if (!StringUtils.isNullOrEmpty(username)){
//拼接记得在and前加空格,否则拼接后sql语句错误
sql.append(" and u.userName like ?");
//index:0
list.add("%"+username+"%");
}
if (userRole>0){
//拼接记得在and前加空格,否则拼接后sql语句错误
sql.append(" and u.userRole = ?");
//index:1
list.add(userRole);
}
//把list转换为数组
Object[] params = list.toArray();
//输出最后完整的sql语句
System.out.println("UserDaoImpl->getUserCount:"+sql.toString());
rs = BaseDao.execute(connection, sql.toString(), params, rs, pstm);
if (rs.next()){
//从结果集中获取最终的数量
count = rs.getInt("count");
}
BaseDao.closeResource(connection,pstm,rs);
}
return count;
}
public interface UserService {
//用户登录
public User login(String userCode,String password);
//根据用户Id修改密码
public boolean updatePwd(Integer id, String password) ;
//查询记录数
public int getUserCount(String username,int userRole);
}
@Override
//查询记录数
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;
}
@Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
int userCount = userService.getUserCount(null, 2);
System.out.println(userCount);
}
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;
}
}
}
public interface UserDao {
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
//修改当前用户密码
public int updatePwd(Connection connection,int id,String password) throws SQLException;
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
//通过条件查询userlist
public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize) throws SQLException;
}
//通过条件查询userlist
public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException {
PreparedStatement pstm=null;
ResultSet rs=null;
int startIndex=0;
List<User> userlist = new ArrayList<User>();
if (connection!=null){
StringBuffer sql = new StringBuffer();
//此处sql与查询用户总数的sql不同
sql.append("select u.*,r.roleName as userRoleName from smbms_user u ,smbms_role r where u.userRole=r.id");
List<Object> 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);
}
//数据库中分页使用limit startIndex,pageSize(当前页起始页码和页面容量两个参数)
//其中startIndex=(当前页码-1)*页面容量;order by:排序;DESC:降序
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("UserDaoImpl->getUserList"+sql.toString());
rs = BaseDao.execute(connection, sql.toString(), params, rs, pstm);
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"));
user.setUserRoleName(rs.getString("userRoleName"));
userlist.add(user);
}
BaseDao.closeResource(null,pstm,rs);
}
return userlist;
}
public interface UserService {
//用户登录
public User login(String userCode,String password);
//根据用户Id修改密码
public boolean updatePwd(Integer id, String password) ;
//查询记录数
public int getUserCount(String username,int userRole);
//根据条件查询用户列表
public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
}
@Override
//根据条件查询用户列表
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
Connection connection=null;
List<User> userList=null;
System.out.println("queryUserName--->"+queryUserName);
System.out.println("queryUserRole--->"+queryUserRole);
System.out.println("currentPageNo--->"+currentPageNo);
System.out.println("pageSize--->"+pageSize);
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;
}
为了职责分明,可以把对角色的操作单独放在一个包里和pojo对应
public interface RoleDao {
//获取角色列表
public List<Role> getRoleList(Connection connection) throws SQLException;
}
public class RoleDaoImpl implements RoleDao{
@Override
//获取角色列表
public List<Role> getRoleList(Connection connection) throws SQLException {
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, sql, params, rs, pstm);
while (rs.next()){
Role role = new Role();
role.setId(rs.getLong("id"));
role.setRoleCode(rs.getString("roleCode"));
role.setRoleName(rs.getString("roleName"));
}
BaseDao.closeResource(null,pstm,rs);
}
return rolelist;
}
}
public interface RoleService {
//获取角色列表
public List<Role> getRoleList();
}
public class RoleServiceImpl implements RoleService{
//引入Dao
private RoleDao roleDao;
public RoleServiceImpl() {
roleDao=new RoleDaoImpl();
}
@Override
//获取角色列表
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;
}
}
//重点难点:根据前端页面userlist.jsp获取到的数据实现方法
public 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();
List<User> userList=null;
//下面主要完成userService.getUserList()参数的设置
//第一次走分页请求,一定是第一页,页面容量固定
//可以写在配置文件中方便后期修改
int pageSize=5;
int currentPageNo=1;
if (queryUserName==null){
queryUserName="";
}
if (temp!=null && !temp.equals("")){
//给下拉列表查询赋值:0,1,2,3
queryUserRole=Integer.parseInt(temp);
}
if (pageIndex!=null){
currentPageNo = Integer.parseInt(pageIndex);
}
//获取用户的总数(分页:上一页,下一页的情况)
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
//总页数支持
PageSupport pageSupport = new PageSupport();
pageSupport.setPageSize(pageSize);
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setTotalCount(totalCount);
int totalPageCount = pageSupport.getTotalPageCount();
//控制尾页和首页
//如果前端获取的当前页小于1,显示第一页
if (currentPageNo<1){
currentPageNo=1;
}
//如果前端获取的当前页大于总页数,显示最后一页
if (currentPageNo>totalPageCount){
currentPageNo=totalPageCount;
}
//将获取到的用户列表展示
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);
req.setAttribute("totalPageCount",totalPageCount);
//返回前端
try {
req.getRequestDispatcher("userlist.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
注意:页面跳转程序使用了位于rollpage.js程序里的page-nav函数,要明白它两个参数的意义
rollpage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
<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)'>GObutton>
span>
div>
body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/rollpage.js">script>
html>
rollpage.js
//page_nav有两个参数
//参数1:document.forms 是得到userlist.jsp页面中所有的表单集合
//document.forms(0) 是得到userlist.jsp页面中的第一个from表单对象
//参数2:是计算好后的当前页码
function page_nav(frm,num){
//为userlist.jsp页面中第一个from表单中的
//把计算好的num单签页码赋值给
//谷歌浏览器无法上下翻页,但是360极速模式可以,证明不是代码问题,是浏览器兼容问题
frm.pageIndex.value = num;
//frm.action += num;
//相当于提交userlist.jsp页面中第一个from表单==点击查询按钮
frm.submit();
}
function jump_to(frm,num){
//alert(num);
//验证用户的输入
var regexp=/^[1-9]\d*$/;
var totalPageCount = document.getElementById("totalPageCount").value;
//alert(totalPageCount);
if(!regexp.test(num)){
alert("请输入大于0的正整数!");
return false;
}else if((num-totalPageCount) > 0){
alert("请输入小于总页数的页码");
return false;
}else{
page_nav(frm,num);
}
}
增删改功能实现可根据总体架构,利用前端提交表单或AJAX、href方式与servlet交互,进而执行后端程序进行数据库操作。目前实现了密码修改、退出系统以及用户管理的增查,删与改因为涉及到AJAX需要后期完善;订单管理和供应商管理参照用户管理设计即可。(浏览器界面涉及较多前端知识)