超市管理系统(smbms)作为每个计算机专业的大学生都是一个很好的练手项目,逻辑层次分明,基础功能包括用户的登录和注销,用户和供应商以及订单信息的增删查改的基础功能。可以帮助我们更好的加深理解三层架构的理念,本项目作为纯JavaWeb版,不涉及Spring和SpringBoot的知识,就是帮助我们从底层和从源代码开始理解,为以后的微服务和作铺垫。
系统整体架构简略图如下:
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!--jstl表达式-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
在resources文件夹下新建db.properties用于存放数据库的配置及文件(驱动,路径,用户名和密码)
#在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8,使用安全连接,可以将数据类型为Date的字段设置为空值
url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=true&zeroDateTimeBehavior=convertToNull
username=root
password=123456
#连接数据库的驱动
driver=com.mysql.cj.jdbc.Driver
新建DBDao类,编写数据库的公共类就是将连接数据库和关闭资源和查询操作设置为静态方法或静态类型,方便用户重复的调用方法,极大的提高了项目增删查改的效率。
public class DBDao {
private static String url;
private static String username;
private static String password;
private static String driver;
static {
//读取db.properties的数据转变为数据流
InputStream is = DBDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties=new Properties();
try {
properties.load(is);//加载数据
} catch (IOException e) {
e.printStackTrace();
}
//获取各项资源
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
driver=properties.getProperty("driver");
}
//数据库连接操作
public static Connection getCon(){
Connection con=null;
try {
Class.forName(driver);
con=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//查询操作
public static ResultSet executeQuery(Connection con, PreparedStatement ps,ResultSet rst,String sql,Object[] params) throws SQLException {
ps=con.prepareStatement(sql);//预编译
for (int i = 0; i <params.length; i++) {
//占位符从1开始,但是数组是从0开始的
ps.setObject(i+1,params[i]);
}
rst=ps.executeQuery();
return rst;//返回结果集
}
//增加删除修改操作
public static int executeUpdate(Connection con,PreparedStatement ps,String sql,Object[] params) throws SQLException {
ps=con.prepareStatement(sql);
for (int i = 0; i <params.length ; i++) {
ps.setObject(i+1,params[i]);
}
int row=ps.executeUpdate();
return row;//返回受影响的行数
}
//数据库关闭操作
public static void getClose(Connection con,PreparedStatement ps,ResultSet rst){
if (rst!=null){//若不为空,执行关闭操作
try {
rst.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ps!=null){
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在Filter包中编写字符编码过滤器的作用是将前端弹框消息文字显示为中文,要记住在设置完后一定要添加filterChain.doFilter()方法,否则无法作用。
public class CharsetEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//设置字符编码集为UTF-8
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {}
}
在之后web.xml中配置Servlet即可。
<filter>
<filter-name>filterfilter-name>
<filter-class>filter.CharsetEncodingFilterfilter-class>
filter>
<filter-mapping>
<filter-name>filterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
tomcat配置如下,方便进行功能的服务测试
编写实体类一定要做到与数据库的表格字段一一对应,包括set get方法和toString方法。以User实体类部分代码为例:
通过tomcat跳转到登录页面,输入用户名与密码,通过对比数据库存放的数据来判断是否登录成功,若匹配成功,则跳转到后台的首页,若匹配失败,则会出现错误信息,无法登录,也不能看到后台首页。
登录流程图:
后台首页就是登陆成功出现的页面,在web.xml中配置Servlet即可。
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
只要涉及User类的数据,并且与数据库打交道的方法,此接口只存放方法,如需之后添加方法,都存放在此接口中。
public interface UserDao {
//通过userCode获取User
public User getLoginUser(Connection connection, String userCode)throws Exception;
}
此类的作用就是覆写以上接口的全部方法,用于数据库的连接,关闭,调用查询或增删查改方法,起到service层和数据库的桥梁作用。
@Override
public class UserDaoImpl implements UserDao{
public User getLoginUser(Connection connection, String userCode)
throws Exception {
//变量作用域适用于此方法内
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
if(null != connection){
String sql = "select * from smbms_user where userCode=?";
//sql中需要传入的参数
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("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.getTimestamp("creationDate"));
user.setModifyBy(rs.getInt("modifyBy"));
user.setModifyDate(rs.getTimestamp("modifyDate"));
}
//执行关闭资源,connnection在service层还要用,所以无需关闭
BaseDao.closeResource(null, pstm, rs);
}
return user;
}
}
此接口与Dao接口功能类似,但是里面的方法只用于进行事务(登录用户,查询用户,删除用户)的操作,只需调用daoImpl中的方法就可以操作数据库了,之后增加类似事务,只要往里面添加方法就行。
public interface UserService {
//用户登录,只需要传入用户名和密码
public User login(String userCode, String userPassword);
}
此类覆写以上接口全部方法,功能相似。
public class UserServiceImpl implements UserService{
//引用UserDao接口,否则无法调用里面的方法,无法与数据库进行连接以操作数据库,且此变量是此类的全局变量。
private UserDao userDao;
public UserServiceImpl(){
userDao = new UserDaoImpl();
}
@Override
public User login(String userCode, String userPassword) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
//调用userDao中的方法
user = userDao.getLoginUser(connection, userCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭connection即可
BaseDao.closeResource(connection, null, null);
}
//若密码匹配不正确,则user返回null
if(null != user){
if(!user.getUserPassword().equals(userPassword))
user = null;
}
return user;
}
}
此类用于前端与后端的交互作用,在登陆功能这一块,就是将用户输入的用户名与密码拿来,去调用service层,再通过service层调用dao层,再调用数据库,与数据库中的用户名和密码相匹配,若匹配失败,则提示相关信息,并无法跳转到下一个页面,若匹配成功,则会页面跳转到下一个页面。
在编写前先编写一个工具类,用于存放所有要用到的常量。
public class Constants {
public final static String USER_SESSION = "userSession";
public final static String SYS_MESSAGE = "message";
public final static int pageSize = 5;
}
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("login ============ " );
//从前端框中获取用户输入的用户名和密码
String userCode = request.getParameter("userCode");
String userPassword = request.getParameter("userPassword");
//调用service方法,进行用户匹配
UserService userService = new UserServiceImpl();
User user = userService.login(userCode,userPassword);
if(null != user){//登录成功
//放入session
request.getSession().setAttribute(Constants.USER_SESSION, user);
//页面重定向(frame.jsp)
response.sendRedirect("jsp/frame.jsp");
}else{
//登陆失败,页面跳转(login.jsp)带出提示信息--转发
request.setAttribute("error", "用户名或密码不正确");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
<servlet>
<servlet-name>LoginServletservlet-name>
<servlet-class>cn.smbms.servlet.user.LoginServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/login.dourl-pattern>
servlet-mapping>
需求:
解决办法::移除常量的Sessionid,因为Sessionid是唯一的:
public class LogoutServlet extends HttpServlet {
public LogoutServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//清除session
request.getSession().removeAttribute(Constants.USER_SESSION);
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
public void init() throws ServletException {
}
}
注册注销功能的servlet
<servlet>
<servlet-name>LogoutServletservlet-name>
<servlet-class>cn.smbms.servlet.user.LogoutServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LogoutServletservlet-name>
<url-pattern>/jsp/logout.dourl-pattern>
servlet-mapping>
// 增加用户信息
public int add(Connection connection, User user)throws Exception;
// 通过条件查询-userList
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;
// 通过条件查询-用户表记录数
public int getUserCount(Connection connection, String userName, int userRole)throws Exception;
// 通过userId删除user
public int deleteUserById(Connection connection, Integer delId)throws Exception;
//通过userId获取user
public User getUserById(Connection connection, String id)throws Exception;
//修改用户信息
public int modify(Connection connection, User user)throws Exception;
// 修改当前用户密码
public int updatePwd(Connection connection, int id, String pwd)throws Exception;
@Override
//增加用户信息
public int add(Connection connection, User user) throws Exception {
PreparedStatement pstm = null;
//定义返回受影响的行数
int updateRows = 0;
if(null != connection){
//编写sql语句
String sql = "insert into smbms_user (userCode,userName,userPassword," +
"userRole,gender,birthday,phone,address,creationDate,createdBy) " +
"values(?,?,?,?,?,?,?,?,?,?)";
//需要的参数
Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),
user.getUserRole(),user.getGender(),user.getBirthday(),
user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()};
//调用封装的方法
updateRows = BaseDao.execute(connection, pstm, sql, params);
//关闭资源
BaseDao.closeResource(null, pstm, null);
}
return updateRows;
}
@Override
//模糊查询
public List<User> getUserList(Connection connection, String userName,int userRole,int currentPageNo, int pageSize)
throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<User> userList = new ArrayList<User>();
if(connection != null){
//StringBuffer可以用来追加字符串
StringBuffer sql = new StringBuffer();
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<Object>();
//若追加的userName不为空
if(!StringUtils.isNullOrEmpty(userName)){
//and前面有空格!!!
sql.append(" and u.userName like ?");
//根据用户名模糊查询
list.add("%"+userName+"%");
}
if(userRole > 0){
//根据用户角色模糊查询
sql.append(" and u.userRole = ?");
list.add(userRole);
}
//降序排序
sql.append(" order by creationDate DESC limit ?,?");
//实现查询结果的分页
currentPageNo = (currentPageNo-1)*pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, 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"));
_user.setUserRoleName(rs.getString("userRoleName"));
//将取出的值添加到集合当中
userList.add(_user);
}
BaseDao.closeResource(null, pstm, rs);
}
//返回集合
return userList;
}
@Override
//根据Id删除用户
public int deleteUserById(Connection connection,Integer delId) throws Exception {
PreparedStatement pstm = null;
int flag = 0;
if(null != connection){
String sql = "delete from smbms_user where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
//根据用户Id查询用户数据
public User getUserById(Connection connection, String id) throws Exception {
User user = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if(null != connection){
String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
Object[] params = {id};
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("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.getTimestamp("creationDate"));
user.setModifyBy(rs.getInt("modifyBy"));
user.setModifyDate(rs.getTimestamp("modifyDate"));
user.setUserRoleName(rs.getString("userRoleName"));
}
BaseDao.closeResource(null, pstm, rs);
}
//返回查询到的数据
return user;
}
@Override
//更新用户信息
public int modify(Connection connection, User user) throws Exception {
int flag = 0;
PreparedStatement pstm = null;
if(null != connection){
String sql = "update smbms_user set userName=?,"+
"gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
user.getModifyDate(),user.getId()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
//更新密码
public int updatePwd(Connection connection, int id, String pwd)
throws Exception {
int flag = 0;
PreparedStatement pstm = null;
if(connection != null){
String sql = "update smbms_user set userPassword= ? where id = ?";
Object[] params = {pwd,id};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
//根据用户名和角色查询用户数量
public int getUserCount(Connection connection, String userName, int userRole)
throws Exception {
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");
List<Object> list = new ArrayList<Object>();
if(!StringUtils.isNullOrEmpty(userName)){
sql.append(" and u.userName like ?");
list.add("%"+userName+"%");
}
if(userRole > 0){
sql.append(" and u.userRole = ?");
list.add(userRole);
}
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
if(rs.next()){
count = rs.getInt("count");
}
BaseDao.closeResource(null, pstm, rs);
}
return count;
}
public interface UserService {
// 增加用户信息
public boolean add(User user);
//用户登录
public User login(String userCode, String userPassword);
//根据条件查询用户列表
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
// 根据条件查询用户表记录数
public int getUserCount(String queryUserName, int queryUserRole);
// 根据userCode查询出User
public User selectUserCodeExist(String userCode);
// 根据ID删除user
public boolean deleteUserById(Integer delId);
//根据ID查找user
public User getUserById(String id);
//修改用户信息
public boolean modify(User user);
// 根据userId修改密码
public boolean updatePwd(int id, String pwd);
}
@Override
//添加用户信息
public boolean add(User user) {
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
int updateRows = userDao.add(connection,user);
connection.commit();
if(updateRows > 0){
flag = true;
}else{
System.out.println("add failed!");
}
} catch (Exception e) {
e.printStackTrace();
try {
//若事务提交失败,则回滚
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
//在service层进行connection连接的关闭
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
//查询全部用户数据
public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return userList;
}
@Override
//根据userCode查询用户
public User selectUserCodeExist(String userCode) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return user;
}
@Override
//根据Id删除用户
public boolean deleteUserById(Integer delId) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if(userDao.deleteUserById(connection,delId) > 0)
flag = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
//根据Id查询用户
public User getUserById(String id) {
User user = null;
Connection connection = null;
try{
connection = BaseDao.getConnection();
user = userDao.getUserById(connection,id);
}catch (Exception e) {
e.printStackTrace();
user = null;
}finally{
BaseDao.closeResource(connection, null, null);
}
return user;
}
@Override
//修改用户
public boolean modify(User user) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if(userDao.modify(connection,user) > 0)
flag = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
//更新用户密码
public boolean updatePwd(int id, String pwd) {
boolean flag = false;
Connection connection = null;
try{
connection = BaseDao.getConnection();
if(userDao.updatePwd(connection,id,pwd) > 0)
flag = true;
}catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
//得到用户个数
public int getUserCount(String queryUserName, int queryUserRole) {
Connection connection = null;
int count = 0;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, queryUserName,queryUserRole);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return count;
}
添加分页支持的工具类,用于数据结果输出的分页:
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;
}
}
}
public class UserServlet extends HttpServlet {
public UserServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//取出method前端参数
String method = request.getParameter("method");
//调用以下编写的方法
if(method != null && method.equals("add")){
this.add(request, response);
}else if(method != null && method.equals("query")){
this.query(request, response);
}else if(method != null && method.equals("getrolelist")){
this.getRoleList(request, response);
}else if(method != null && method.equals("ucexist")){
this.userCodeExist(request, response);
}else if(method != null && method.equals("deluser")){
this.delUser(request, response);
}else if(method != null && method.equals("view")){
this.getUserById(request, response,"userview.jsp");
}else if(method != null && method.equals("modify")){
this.getUserById(request, response,"usermodify.jsp");
}else if(method != null && method.equals("modifyexe")){
this.modify(request, response);
}else if(method != null && method.equals("pwdmodify")){
this.getPwdByUserId(request, response);
}else if(method != null && method.equals("savepwd")){
this.updatePwd(request, response);
}
//修改密码
private void updatePwd(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//取出UserSession的id
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
//取出页面前端的用户输入的新密码
String newpassword = request.getParameter("newpassword");
boolean flag = false;
//若session不为空,且新密码不为空
if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
//调用service层的方法,将变量O强制类转换获得id
flag = userService.updatePwd(((User)o).getId(),newpassword);
if(flag){
request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录!");
//修改成功后,session注销
request.getSession().removeAttribute(Constants.USER_SESSION);
}else{
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
}else{
//session 或新密码为空
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
//页面跳转
request.getRequestDispatcher("pwdmodify.jsp").forward(request, response);
}
//修改密码时的弹出的信息
private void getPwdByUserId(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = request.getParameter("oldpassword");
Map<String, String> resultMap = new HashMap<String, String>();
if(null == o ){//session过期
resultMap.put("result", "sessionerror");
}else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
resultMap.put("result", "error");
}else{
String sessionPwd = ((User)o).getUserPassword();
if(oldpassword.equals(sessionPwd)){
resultMap.put("result", "true");
}else{//旧密码输入不正确
resultMap.put("result", "false");
}
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
//修改数据
private void modify(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从前端取出数据
String id = request.getParameter("uid");
String userName = request.getParameter("userName");
String gender = request.getParameter("gender");
String birthday = request.getParameter("birthday");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String userRole = request.getParameter("userRole");
User user = new User();
user.setId(Integer.valueOf(id));
user.setUserName(userName);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setModifyDate(new Date());
UserService userService = new UserServiceImpl();
//页面重定向
if(userService.modify(user)){
response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
}else{
request.getRequestDispatcher("usermodify.jsp").forward(request, response);
}
}
//根据id查找数据
private void getUserById(HttpServletRequest request, HttpServletResponse response,String url)
throws ServletException, IOException {
String id = request.getParameter("uid");
if(!StringUtils.isNullOrEmpty(id)){
//调用后台方法得到user对象
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
//将后端数据传到前端页面对应位置
request.setAttribute("user", user);
request.getRequestDispatcher(url).forward(request, response);
}
}
//根据ID删除用户
private void delUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("uid");
Integer delId = 0;
try{
delId = Integer.parseInt(id);
}catch (Exception e) {
delId = 0;
}
HashMap<String, String> resultMap = new HashMap<String, String>();
if(delId <= 0){
resultMap.put("delResult", "notexist");
}else{
UserService userService = new UserServiceImpl();
if(userService.deleteUserById(delId)){
resultMap.put("delResult", "true");
}else{
resultMap.put("delResult", "false");
}
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
//根据userRole查询数据
private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断用户账号是否可用
String userCode = request.getParameter("userCode");
HashMap<String, String> resultMap = new HashMap<String, String>();
if(StringUtils.isNullOrEmpty(userCode)){
//userCode == null || userCode.equals("")
resultMap.put("userCode", "exist");
}else{
UserService userService = new UserServiceImpl();
User user = userService.selectUserCodeExist(userCode);
if(null != user){
resultMap.put("userCode","exist");
}else{
resultMap.put("userCode", "notexist");
}
}
//把resultMap转为json字符串以json的形式输出
//配置上下文的输出类型
response.setContentType("application/json");
//从response对象中获取往外输出的writer对象
PrintWriter outPrintWriter = response.getWriter();
//把resultMap转为json字符串 输出
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();//刷新
outPrintWriter.close();//关闭流
}
//查询角色列表
private void getRoleList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
//把roleList转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(roleList));
outPrintWriter.flush();
outPrintWriter.close();
}
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//查询用户列表
String queryUserName = request.getParameter("queryname");
String temp = request.getParameter("queryUserRole");
String pageIndex = request.getParameter("pageIndex");
int queryUserRole = 0;
UserService userService = new UserServiceImpl();
List<User> userList = null;
//设置页面容量
int pageSize = Constants.pageSize;
//当前页码
int currentPageNo = 1;
/**
* http://localhost:8090/SMBMS/userlist.do
* ----queryUserName --NULL
* http://localhost:8090/SMBMS/userlist.do?queryname=
* --queryUserName ---""
*/
System.out.println("queryUserName servlet--------"+queryUserName);
System.out.println("queryUserRole servlet--------"+queryUserRole);
System.out.println("query pageIndex--------- > " + pageIndex);
if(queryUserName == null){
queryUserName = "";
}
if(temp != null && !temp.equals("")){
queryUserRole = Integer.parseInt(temp);
}
if(pageIndex != null){
try{
currentPageNo = Integer.valueOf(pageIndex);
}catch(NumberFormatException e){
response.sendRedirect("error.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);
request.setAttribute("userList", userList);
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
request.setAttribute("roleList", roleList);
request.setAttribute("queryUserName", queryUserName);
request.setAttribute("queryUserRole", queryUserRole);
request.setAttribute("totalPageCount", totalPageCount);
request.setAttribute("totalCount", totalCount);
request.setAttribute("currentPageNo", currentPageNo);
request.getRequestDispatcher("userlist.jsp").forward(request, response);
}
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("add()================");
String userCode = request.getParameter("userCode");
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
String gender = request.getParameter("gender");
String birthday = request.getParameter("birthday");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String userRole = request.getParameter("userRole");
User user = new User();
user.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setAddress(address);
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user.setGender(Integer.valueOf(gender));
user.setPhone(phone);
user.setUserRole(Integer.valueOf(userRole));
user.setCreationDate(new Date());
user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
UserService userService = new UserServiceImpl();
if(userService.add(user)){
response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
}else{
request.getRequestDispatcher("useradd.jsp").forward(request, response);
}
}
public void init() throws ServletException {
}
}
<servlet>
<servlet-name>LoginServletservlet-name>
<servlet-class>cn.smbms.servlet.user.LoginServletservlet-class>
servlet>
<servlet>
<servlet-name>LogoutServletservlet-name>
<servlet-class>cn.smbms.servlet.user.LogoutServletservlet-class>
servlet>
<servlet>
<servlet-name>UserServletservlet-name>
<servlet-class>cn.smbms.servlet.user.UserServletservlet-class>
servlet>
<servlet>
<servlet-name>ProviderServletservlet-name>
<servlet-class>cn.smbms.servlet.provider.ProviderServletservlet-class>
servlet>
<servlet>
<servlet-name>BillServletservlet-name>
<servlet-class>cn.smbms.servlet.bill.BillServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/login.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServletservlet-name>
<url-pattern>/jsp/logout.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>UserServletservlet-name>
<url-pattern>/jsp/user.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>ProviderServletservlet-name>
<url-pattern>/jsp/provider.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>BillServletservlet-name>
<url-pattern>/jsp/bill.dourl-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingfilter-name>
<filter-class>cn.smbms.filter.CharacterEncodingfilter-class>
filter>
<filter-mapping>
<filter-name>CharacterEncodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>SysFilterfilter-name>
<filter-class>cn.smbms.filter.SysFilterfilter-class>
filter>
<filter-mapping>
<filter-name>SysFilterfilter-name>
<url-pattern>/jsp/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
web-app>
除了用户相关操作外,另外还有订单和供应商也与上述步骤类似,请自行编写!