项目搭建
1.搭建maven web项目
2.配置tomcat
3.测试项目能否成功启动
4.导入项目中可能会遇到的jar包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
5.创建项目包结构
6.编写实体类 ORM映射:表-类映射
User,Role,Bill,Provider
7.编写基础公共类
7.1 数据库配置文件database.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true&user=root&password=123456
user=root
password=123456
7.2 编写数据库公共类
主要的工作为:
package xyz.yiui.dao;
import java.io.IOException;
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 is=BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
}
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Connection connection=null;
Class.forName(driver);
connection= DriverManager.getConnection(url,username,password);
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++){
preparedStatement.setObject(i+1,params[i]);
}
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++){
preparedStatement.setObject(i+1,params[i]);
}
int ans=preparedStatement.executeUpdate();
return ans;
}
public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) {
boolean flag=true;
if(resultSet!=null){
try{
resultSet.close();
resultSet=null;
}catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if(preparedStatement!=null){
try{
preparedStatement.close();
preparedStatement=null;
}catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if(connection!=null){
try{
connection.close();
connection=null;
}catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
7.3 编写字符编码过滤器
package xyz.yiui.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
在web.xml里注册
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>xyz.yiui.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
8.导入静态资源
登录功能实现
1.编写前端页面login.jsp
2.设置首页
在web.xml里配置
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3.编写dao层 用户登录的接口
3.1 编写dao接口UserDao
package xyz.yiui.dao.user;
import xyz.yiui.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public interface UserDao {
public User getLoginUser(Connection connection,String userCode) throws SQLException;
}
3.2 编写对应的实现类UserDaoImpl
package xyz.yiui.dao.user;
import xyz.yiui.dao.BaseDao;
import xyz.yiui.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao{
@Override
public User getLoginUser(Connection connection, String userCode) throws SQLException {
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
User user=null;
if(connection!=null){
String sql="select * from smbms_user where userCode=?";
Object[] params={userCode};
resultSet= BaseDao.execute(connection,resultSet,preparedStatement,sql,params);
if(resultSet.next()){
user=new User();
user.setId(resultSet.getInt("id"));
user.setUserCode(resultSet.getString("userCode"));
user.setUserName(resultSet.getString("userName"));
user.setUserPassword(resultSet.getString("userPassword"));
user.setGender(resultSet.getInt("gender"));
user.setBirthday(resultSet.getDate("birthday"));
user.setPhone(resultSet.getString("phone"));
user.setAddress(resultSet.getString("address"));
user.setUserRole(resultSet.getInt("userRole"));
user.setCreatedBy(resultSet.getInt("createdBy"));
user.setCreationDate(resultSet.getTimestamp("creationDate"));
user.setModifyBy(resultSet.getInt("modifyBy"));
user.setModifyDate(resultSet.getTimestamp("modifyDate"));
}
BaseDao.closeResource(connection,preparedStatement,resultSet);
}
return user;
}
}
4.编写业务层service 用户登录
4.1 业务层接口
package xyz.yiui.service.user;
import xyz.yiui.pojo.User;
public interface UserService {
public User login(String userCode,String password);
}
4.2 业务层实现类
如果密码不正确,设user为空。
package xyz.yiui.service.user;
import org.junit.jupiter.api.Test;
import xyz.yiui.dao.BaseDao;
import xyz.yiui.dao.user.UserDao;
import xyz.yiui.dao.user.UserDaoImpl;
import xyz.yiui.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public class UserServiceImpl implements UserService{
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);
if(!password.equals(user.getUserPassword())) user=null;
}catch (SQLException | ClassNotFoundException e){
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
@Test
public void test(){
UserServiceImpl userService=new UserServiceImpl();
User admin=userService.login("admin","111");
System.out.println(admin.getUserPassword());
}
}
4.3 编写测试类
@Test
public void test(){
UserServiceImpl userService=new UserServiceImpl();
User admin=userService.login("admin","111");
System.out.println(admin.getUserPassword());
}
5.编写控制层servlet
5.1 编写代码
package xyz.yiui.servlet.user;
import xyz.yiui.pojo.User;
import xyz.yiui.service.user.UserService;
import xyz.yiui.service.user.UserServiceImpl;
import xyz.yiui.util.Constans;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@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");
UserService userService=new UserServiceImpl();
User user=userService.login(userCode,userPassword);
if(user!=null){
req.getSession().setAttribute(Constans.USER_SESSION,user);
resp.sendRedirect("jsp/frame.jsp");
}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);
}
}
utils里的Constans放常量
package xyz.yiui.util;
public class Constans {
public final static String USER_SESSION="userSession";
}
5.2 注册servlet
在web.xml里注册
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>xyz.yiui.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
登录功能优化
1.注销:移除session,返回登陆页面
1.1servlet
package xyz.yiui.servlet.user;
import xyz.yiui.util.Constans;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().removeAttribute(Constans.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
1.2 web.xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>xyz.yiui.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
2.登录拦截器
2.1 编写代码
package xyz.yiui.filter;
import xyz.yiui.pojo.User;
import xyz.yiui.util.Constans;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
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 request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) resp;
User user=(User) request.getSession().getAttribute(Constans.USER_SESSION);
if(user==null){
response.sendRedirect("/smbms/error.jsp");
}
else{
chain.doFilter(req,resp);
}
}
@Override
public void destroy() {
}
}
2.2 注册web.xml
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>xyz.yiui.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
密码修改
1.导入前端资源
2.编写代码dao层
2.1 userdao接口
public int updatePwd(Connection connection,int id,String password) throws SQLException;
2.2 userdaoimpl实现类
@Override
public int updatePwd(Connection connection, int id, String password) throws SQLException {
PreparedStatement preparedStatement=null;
int ans=0;
if(connection!=null){
String sql="update smbms_user set userPassword = ? where id = ?";
Object params[]={password,id};
ans=BaseDao.execute(connection,preparedStatement,sql,params);
BaseDao.closeResource(null,preparedStatement,null);
}
return ans;
}
3.service层
3.1 接口UserService
public boolean updatePwd(int id, String password);
3.2实现类UserServiceImpl
@Override
public boolean updatePwd(int id, String password) {
boolean flag=false;
Connection connection=null;
try{
connection=BaseDao.getConnection();
if(userDao.updatePwd(connection,id,password)>0){
flag=true;
}
}catch (SQLException | ClassNotFoundException e){
e.printStackTrace();
}
finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
4.servlet层UserServlet
提高servlet复用,写到方法里
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object o=req.getSession().getAttribute(Constans.USER_SESSION);
String newpassword=req.getParameter("newpassword");
System.out.println("UserServlet"+newpassword);
boolean flag=false;
if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService=new UserServiceImpl();
flag=userService.updatePwd( ((User)o).getId(),newpassword );
if(flag){
req.setAttribute("message","update success,please logout");
System.out.println("update success,please logout");
req.getSession().removeAttribute(Constans.USER_SESSION);
}
else{
req.setAttribute("message","update failed");
System.out.println("update failed");
}
}
else{
req.setAttribute("message","newpassword wrong");
System.out.println("newpassword wrong");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
System.out.println("update suceess");
}
在doGet里判断
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method=req.getParameter("method");
if(method.equals("savepwd")&&method!=null){
this.updatePwd(req,resp);
}
}
密码修改优化
在输入旧密码的时候就应该匹配旧密码是否正确,如果都放到后端去判断的话,不太符合逻辑需求,使用Ajax在前端进行判断。
1.导入jar包依赖 编写Ajax代码
借助阿里巴巴的工具类JSONArray实现格式的转换,所以先导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
$.ajax({
type:"GET",
url:path+"/jsp/user.do",
data:{method:"pwdmodify",oldpassword:oldpassword.val()},
dataType:"json",
success:function(data){
if(data.result == "true"){
validateTip(oldpassword.next(),{"color":"green"},imgYes,true);
}else if(data.result == "false"){
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 11oldpassword error",false);
}else if(data.result == "sessionerror"){
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 22session timeout",false);
}else if(data.result == "error"){
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 33oldpassword null",false);
}
},
error:function(data){
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 44req error",false);
}
});
2.修改session过期时间web.xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>
3.编写servlet
首先进行判断,通过原生代码处理让map里的东西变为json
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object o=req.getSession().getAttribute(Constans.USER_SESSION);
String newpassword=req.getParameter("newpassword");
System.out.println("UserServlet"+newpassword);
boolean flag=false;
if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService=new UserServiceImpl();
flag=userService.updatePwd( ((User)o).getId(),newpassword );
if(flag){
req.setAttribute("message","update success,please logout");
System.out.println("update success,please logout");
req.getSession().removeAttribute(Constans.USER_SESSION);
}
else{
req.setAttribute("message","update failed");
System.out.println("update failed");
}
}
else{
req.setAttribute("message","newpassword wrong");
System.out.println("newpassword wrong");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
System.out.println("update suceess");
}
public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
Object o=req.getSession().getAttribute(Constans.USER_SESSION);
String oldpassword=req.getParameter("oldpassword");
Map<String,String> resultMap=new HashMap<String,String>();
if(o==null){
resultMap.put("result","sessionerror");
}else if(StringUtils.isNullOrEmpty(oldpassword)){
resultMap.put("result","error");
}
else{
String userpwd=((User)o).getUserPassword();
if(oldpassword.equals(userpwd)){
resultMap.put("result","true");
}
else{
resultMap.put("result","false");
}
}
try{
resp.setContentType("application/json");
PrintWriter writer=resp.getWriter();
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
}catch (IOException e){
e.printStackTrace();
}
}
用户管理
1.导入分页工具类PageSupport.java
OOP三大特性:封装(属性私有、get/set、在set里限定一些不安全情况)
package xyz.yiui.util;
public class PageSupport {
private int currentPageNo = 1;
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.用户列表页面导入userlist.jsp跟rollpage.jsp
3.获取用户数量
3.1 编写代码dao层
3.1.1 UserDao
public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
3.1.2 UserDaoImpl
@Override
public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
int cnt=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)){
sql.append("and u.userName like ?");
list.add("%"+username+"%");
}
if(userRole>0){
sql.append("and u.userRole = ?");
list.add(userRole);
}
Object[] objects=list.toArray();
System.out.println("UserDaoImpl->getUserCount"+sql.toString());
resultSet=BaseDao.execute(connection,resultSet,preparedStatement, String.valueOf(sql),objects);
if(resultSet.next()){
cnt=resultSet.getInt("count");
}
BaseDao.closeResource(null,preparedStatement,resultSet);
}
return cnt;
}
3.2 编写代码业务层
3.2.1 UserService
public int getUserCount(String username,int userRole);
3.2.2 UserServiceImpl
@Override
public int getUserCount(String username, int userRole) {
Connection connection=null;
int cnt=0;
try{
connection=BaseDao.getConnection();
cnt=userDao.getUserCount(connection,username,userRole);
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection,null,null);
}
return cnt;
}
3.3 测试
@Test
public void test_getUserCount(){
UserServiceImpl userService=new UserServiceImpl();
int ans=userService.getUserCount(null,1);
System.out.println(ans);
}
4.获取用户列表
在获取用户列表的时候要考虑到分页问题。 数据库中,分页使用limit 语法 limit startindex,pagesize 比如0,5表示第一页,5,5表示第二页,10,5表示第三页。 startindex=(当前页面-1)*页面大小
4.1编写代码dao层
4.1.1 UserDao
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;
4.1.2 UserDaoImpl
@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 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>();
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.append(" order by 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, rs,pstm , 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;
}
4.2 编写代码业务层
4.2.1 UserService
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
4.2.2 UserServiceImpl
@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;
}
4.3 测试
@Test
public void test_getUserList(){
UserServiceImpl userService=new UserServiceImpl();
List<User> ans=userService.getUserList(null,3,1,5);
for(User t:ans) System.out.println(t);
}
改为2以后,查询第2页的数据
5.获取角色列表
5.1编写代码dao层
5.1.1 RoleDao
public List<Role> getRoleList(Connection connection)throws SQLException;
5.1.2 RoleDaoImpl
@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, rs,pstm , 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;
}
5.2 编写代码业务层
5.2.1 RoleService
public List<Role> getRoleList();
5.2.2 RoleServiceImpl
public class RoleServiceImpl implements RoleService{
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 (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return roleList;
}
}
5.3 测试
@Test
public void test_getRoleList(){
RoleServiceImpl roleService=new RoleServiceImpl();
List<Role> ans=roleService.getRoleList();
for(Role t:ans) System.out.println(t);
}
6.编写servlet
- 获取用户的前端的数据,用于查询
- 判断请求是否要执行,看参数的值进行判断
- 为了实现分页,需要计算出当前页面,总页面等,借助分页工具类实现
- 用户列表显示
- 将得到的数据返回给前端
UserServlet里
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method=req.getParameter("method");
if(method.equals("savepwd")&&method!=null){
this.updatePwd(req,resp);
}else if(method.equals("pwdmodify")&&method!=null){
this.pwdmodify(req,resp);
}else if(method.equals("query")&&method!=null){
this.query(req,resp);
}
}
public void query(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
String queryUserName=req.getParameter("queryname");
String tmp=req.getParameter("queryUserRole");
String pageIndex=req.getParameter("pageIndex");
int queryUserRole=0;
UserServiceImpl userService=new UserServiceImpl();
RoleServiceImpl roleService=new RoleServiceImpl();
int pageSize=Constans.PAGESIZE;
int currentPageNo=1;
if(queryUserName==null){
queryUserName="";
}
System.out.println(tmp);
System.out.println(queryUserRole);
if(!StringUtils.isNullOrEmpty(tmp)){
queryUserRole= Integer.parseInt(tmp);
System.out.println(queryUserRole);
}
if(pageIndex!=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.getTotalPageCount();
if(currentPageNo<1) currentPageNo=1;
if(currentPageNo>totalPageCount) currentPageNo=totalPageCount;
List<User> userList=userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
req.setAttribute("userList",userList);
List<Role>roleList=roleService.getRoleList();
req.setAttribute("roleList",roleList);
req.setAttribute("totalCount",totalCount);
req.setAttribute("currentPageNo",currentPageNo);
req.setAttribute("totalPageCount",totalPageCount);
req.setAttribute("queryUserName",queryUserName);
req.setAttribute("queryUserRole",queryUserRole);
try{
req.getRequestDispatcher("userlist.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
一切的增删改操作都需要处理事务,ACID
7.增加用户
7.1 编写UserDao
public int add(Connection connection, User user)throws Exception;
7.2 编写UserDaoImpl
@Override
public int add(Connection connection, User user) throws Exception {
PreparedStatement pstm = null;
int updateRows = 0;
if(null != connection){
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;
}
7.3 编写UserService
public boolean add(User user);
7.4 编写UserServiceImpl
@Override
public boolean add(User user) {
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);
int updateRows = userDao.add(connection,user);
connection.commit();
if(updateRows > 0){
flag = true;
System.out.println("add success!");
}else{
System.out.println("add failed!");
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
7.5 编写UserServlet
在doget里添加
}else if(method != null && method.equals("add")){
this.add(req, resp);
}
add函数如下
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) {
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(Constans.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);
}
}
8.修改用户信息
8.1 编写UserDao
public int modify(Connection connection, User user)throws Exception;
8.2 编写UserDaoImpl
@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;
}
8.3 编写UserService
public boolean modify(User user);
8.4 编写UserServiceImpl
@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;
}
8.5 编写UserServlet
else if(method != null && method.equals("modify")){
this.getUserById(req, resp,"usermodify.jsp");
}else if(method != null && method.equals("modifyexe")){
this.modify(req, resp);
}
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(Constans.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);
}
}
9.删除用户
9.1 编写UserDao
public int deleteUserById(Connection connection, Integer delId)throws Exception;
9.2 编写UserDaoImpl
@Override
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;
}
9.3 编写UserService
public boolean deleteUserById(Integer delId);
9.4 编写UserServiceImpl
@Override
public boolean deleteUserById(Integer delId) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);
connection.commit();
if(userDao.deleteUserById(connection,delId) > 0)
flag = true;
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
9.5 编写UserServlet
在doget里添加
else if(method != null && method.equals("deluser")){
this.delUser(req, resp);
}
删除方法如下:
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");
}
}
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
10.查看用户详细信息
10.1 编写UserDao
public User getUserById(Connection connection, String id)throws Exception;
10.2 编写UserDaoImpl
@Override
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, rs,pstm , 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;
}
10.3 编写UserService
public User getUserById(String id);
10.4 编写UserServiceImpl
@Override
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;
}
10.5 编写UserServlet
在doGET里添加
else if(method != null && method.equals("view")){
this.getUserById(req, resp,"userview.jsp");
}
private void getUserById(HttpServletRequest request, HttpServletResponse response,String url)
throws ServletException, IOException {
String id = request.getParameter("uid");
if(!StringUtils.isNullOrEmpty(id)){
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
request.setAttribute("user", user);
request.getRequestDispatcher(url).forward(request, response);
}
}
11.完善
11.1添加获取角色列表
在servlet里添加获取角色列表的方法 doGet添加
else if(method != null && method.equals("getrolelist")){
this.getRoleList(req,resp);
}
然后写这个方法,就是得到角色列表,调用之前写好的业务层逻辑即可
private void getRoleList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(roleList));
outPrintWriter.flush();
outPrintWriter.close();
}
11.2 查看相同用户编码的人是否存在
因为在填写的时候,使用了Ajax异步判断相同用户编码的人在数据库里是否已经存在,所以对其进行判断。
11.2.1 UserDao
public User getUserByCode(Connection connection, String userCode)throws Exception;
11.2.2 UserDaoImpl
@Override
public User getUserByCode(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=?";
Object[] params = {userCode};
rs = BaseDao.execute(connection, rs, pstm, 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"));
}
BaseDao.closeResource(null, pstm, rs);
}
return user;
}
11.2.3 userService
public User selectUserCodeExist(String userCode);
11.2.4 userServiceImpl
@Override
public User selectUserCodeExist(String userCode) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
user = userDao.getUserByCode(connection, userCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return user;
}
11.2.5 UserServlet
在doGet里添加判断
else if(method != null && method.equals("ucexist")){
this.userCodeExist(request, response);
}
编写判断函数
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)){
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");
}
}
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
项目地址
|