一、JavaBean
实体类
JavaBean有特定的写法:
- 必须要有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法
一般用来和数据库的字段做映射
ORM:对应关系映射
- 表–>类
- 字段–>属性
- 行记录–>对象
id | name | age | address |
---|---|---|---|
1 | |||
2 |
class People{
private int id;
private String name;
private int age;
private String address;
}
class A{
}
实体类
javaBean有特定的写法
二、MVC三层架构
什么是MVC:Model view Controller 模型、视图、控制器
1、早些年
用户直接访问控制层,控制层就可以直接造作数据库:
servlet---CRUD--->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、相应、试图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序员调用
| |
| |
JDBC
| |
| |
mysql Oracle sqlServet....
2、三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD (Dao)数据持久化对象
View
- 展示数据
- 提供链接发起Servlet请求(a,form,img······)
Controller
- 接受用户的请求:(req:请求参数、session信息······)
- 交给业务层处理对应的代码
- 控制视图的跳转
登录---->接受用户的登录请求---->处理用户的请求(获取用户登录的参数:username,password)--->交给业务层
处理登录业务(判断用户密码是否正确:事物)---->Dao层查询用户名和密码是否正确--->数据库
三、SMBMS项目分析
数据库:
项目如何搭建?
考虑使用不使用Maven?依赖,jar
项目搭建准备
-
搭建一个mavenweb项目
-
配置tomcat
-
测试项目是否可以跑起来
-
导入向目中会用到的jar包
jsp,Servlet,mysql驱动,jstl,standered
-
创建项目包结构
- 编写实体类(javabean)
ORM映射:表-类映射
-
编写基础公共类
-
数据库配置文件
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8 username=root password=123456
-
编写数据库的公共类
//操作数据库的公共类 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 (IOException e) { e.printStackTrace(); } driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); } //获取数据库连接 public static Connection getConnection(){ Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url,username,password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } return conn; } //编写查询公共类 public static ResultSet execute(Connection conn,PreparedStatement pstat,ResultSet set,String sql,Object[] params){ try { pstat = conn.prepareStatement(sql); for (int i = 0;i<params.length;i++){ pstat.setObject(i+1,params[i]); } set = pstat.executeQuery(); } catch (SQLException throwables) { throwables.printStackTrace(); } return set; } //编写增删改公共方法 public static int execute(Connection conn,PreparedStatement pstat,String sql,Object[] params){ int updateRows = 0; try { pstat = conn.prepareStatement(sql); for (int i = 0;i<params.length;i++){ pstat.setObject(i+1,params[i]); } updateRows = pstat.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } return updateRows; } //关闭连接 public static boolean close(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection){ Boolean flag = true; if (resultSet!=null){ try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (preparedStatement!=null){ try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (connection!=null){ try { connection.close(); //GC回收 connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } return flag; } //复写关闭方法 public static boolean close(PreparedStatement preparedStatement,Connection connection){ Boolean flag = true; if (preparedStatement!=null){ try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (connection!=null){ try { connection.close(); //GC回收 connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } return flag; } }
-
字符编码过滤器
-
-
导入静态资源
链接:
提取码:hzak
登录功能实现
-
编写前端页面
-
设置首页
<!--设置欢迎页面--> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list>
-
编写dao层接口实现类
public interface UserDao { //得到要登录的用户 public User getLoginUser(Connection connection, String userCode) throws SQLException; }
-
编写dao接口的实现类
public class UserDaoImp1 implements UserDao { public User getLoginUser(Connection connection, String userCode) throws SQLException { PreparedStatement pstat = 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,pstat,resultSet,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.getDate("creationDate")); user.setModifyBy(resultSet.getInt("modifyBy")); user.setModifyDate(resultSet.getDate("modifyDate")); } BaseDao.close(resultSet,pstat,null); } 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 UserDaoImp1(); } 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.close(null,null,connection); } return user; } }
-
编写Servlet
public class LoginServlet extends HttpServlet { //Servlet:控制层,调用业务层 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet----start---"); //获取用户名和密码 String username = req.getParameter("userCode"); String password = req.getParameter("userPassword"); //和数据库中的密码进行对比,调用业务层 UserService userService = new UserServiceImpl(); User user = userService.login(username,password);//这里可以把人查出来 //查有此人登录 if (user!=null) { //将用户的信息放进Session中 req.getSession().setAttribute(Constants.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 { super.doPost(req, resp); } }
-
注册Servlet
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.zhao.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
-
测试访问以上功能访问成功
登录功能优化
注销功能
思路:移除Session,返回登录页面
public class LogoutServlet 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 {
super.doPost(req, resp);
}
}
注册xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.zhao.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截器优化
编写一个过滤器,并注册xml
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//过滤器,从Session中获取用户
User user = (User)request.getSession().getAttribute(Constants.USER_SESSION);
if (user==null){
response.sendRedirect("/smbms/error.jsp");
}else {
filterChain.doFilter(servletRequest,servletResponse);
}
}
public void destroy() {
}
}
<!--系统拦截:用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.zhao.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
测试,登录,注销,权限。
密码修改
-
导入前端素材
-
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li>
-
-
写项目建议从底层往上写
-
UserDao接口
public interface UserDao { //得到要登录的用户 public User getLoginUser(Connection connection, String userCode) throws SQLException; //修改当前密码 public int updatePwd(Connection connection,int id,int password) throws SQLException; }
-
public class UserDaoImp1 implements UserDao { 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,preparedStatement, resultSet,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.getDate("creationDate")); user.setModifyBy(resultSet.getInt("modifyBy")); user.setModifyDate(resultSet.getDate("modifyDate")); } BaseDao.close(resultSet,preparedStatement,null); } return user; } // 修改当前密码 public int updatePwd(Connection connection, int id, int password) throws SQLException { PreparedStatement pstat = null; int update = 0; if (connection!=null){ String sql = "update smbms_user set userPassword = ? where id = ?"; Object[] params = {password,id}; update = BaseDao.execute(connection,pstat,sql,params); BaseDao.close(null,pstat,null); } return update; } }
-
UserService层
public boolean updatePwd(int id,String pwd);
-
UserService实现类
//修改密码 public boolean updatePwd(int id, String pwd) { Connection conn = null; boolean flag = false; conn = BaseDao.getConnection(); UserDao userDao = new UserDaoImp1(); //修改密码 try { if (userDao.updatePwd(conn,id,pwd)>0){ flag = true; } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.close(null,null,conn); } return flag; }
-
Servlet记得实现复用,需要提出取方法!
//实现Servlet复用 public class UserServlet extends HttpServlet { @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); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } public void updatePwd(HttpServletRequest req, HttpServletResponse resp){ //从Session里面拿id Object attribute = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); System.out.println("UserPassword = "+newpassword); boolean flag = false; System.out.println(attribute!=null); System.out.println(!StringUtils.isNullOrEmpty(newpassword)); if (attribute!=null && newpassword!=null && newpassword.length()!=0){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User)attribute).getId(),newpassword); if (flag){ req.setAttribute("message","修改密码成功,请退出,用新密码登录"); //密码修改成功移除Session req.getSession().removeAttribute(Constants.USER_SESSION); }else { req.setAttribute("message","密码修改失败"); } }else { req.setAttribute("message","新密码有问题"); } try { req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
-
测试
优化密码修改使用Ajax
-
阿里巴巴的fastjson
-
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
-
-
后台代码修改
//验证旧密码,Seesion中有旧密码 public void pwdModify(HttpServletRequest req, HttpServletResponse resp){ //从Session里面拿id Object o = req.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = req.getParameter("oldpassword"); //万能的Map Map<String,String> resultMap = new HashMap<String,String>(); if (o==null){//Session失效或Session过期 resultMap.put("result","sessionerror"); }else if (StringUtils.isNullOrEmpty(oldpassword)){ resultMap.put("result","error"); }else { String userPassword = ((User)o).getUserPassword();//Session中的用户密码 if (oldpassword.equals(userPassword)){ resultMap.put("result","true"); }else { resultMap.put("result","false"); } } try { resp.setContentType("application/json"); Writer writer = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类,转换格式 /* * resultMap = ["result","sessionerror","result","false"] * */ writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
-
测试
用户管理实现
思路:
-
导入分页的工具类
-
用户列表页面导入
- userlist.jsp
- rollpage.jsp
1. 获取用户数量
-
UserDao
//查询用户总数 public int getUserCount(Connection connection,String userName,int userRole)throws SQLException;
-
UserDaoImp1
//查询用户名或者角色查询用户总量 public int getUserCount(Connection connection, String userName, int userRole) throws SQLException { PreparedStatement pstat = 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<Object>();//存我们的参数 if (!StringUtils.isNullOrEmpty(userName)){ sql.append("and u.userName like ? "); list.add("%"+userName+"%");//index:0 } if (userRole>0){ sql.append("and u.userRole = ? "); list.add(userRole);//index:1 } //怎么把list转换为数组 Object[] objects = list.toArray(); System.out.println(sql.toString()); rs = BaseDao.execute(connection,pstat,rs,sql.toString(),objects); if (rs.next()){ count = rs.getInt("count");//从结果集中获取最终的数量 } BaseDao.close(rs,pstat,null); } return count; }
-
UserService
//查询记录数 public int getUserCount(String userName,int userRole);
-
UserServiceLmpI
public int getUserCount(String userName, int userRole) { Connection conn = null; int count = 0; try { conn = BaseDao.getConnection(); count = userDao.getUserCount(conn,userName,userRole); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.close(null,null,conn); } return count; }
2.获取用户列表
-
UserDao
//获取用户列表 public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws Exception;
-
UserDaoImp1
//获取用户列表 public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception { PreparedStatement pstat = null; ResultSet rs = null; List<User> userList = new ArrayList<User>(); 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<Object>();//存我们的参数 if (!StringUtils.isNullOrEmpty(userName)) { sql.append("and u.userName like ? "); list.add("%" + userName + "%");//index:0 } if (userRole > 0) { sql.append("and u.userRole = ? "); list.add(userRole);//index:1 } //在数据库分页中,分页使用limit startIndex,pageSize;总数 //当前页 (当前页-1)*页面大小 //0,5 1 0 01234 //5,5 2 5 56789 //10,5 3 10 1112131415 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,pstat,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); } } return userList; }
-
UserService
public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
-
UserServiceLmpI
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { Connection conn = 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 { conn = BaseDao.getConnection(); userList = userDao.getUserList(conn,queryUserName,queryUserRole,currentPageNo,pageSize); } catch (Exception e) { e.printStackTrace(); }finally { BaseDao.close(null,null,conn); } return userList; }
3.获取角色列表
-
RoleDao
//获取角色列表 public List<Role> getRoleList(Connection connection)throws SQLException;
-
RoleDaolmp1
//获取角色列表 public List<Role> getRoleList(Connection connection) throws SQLException { PreparedStatement pstat = 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,pstat,rs,sql,params); while (rs.next()){ Role _role = new Role(); _role.setId(rs.getInt("id")); _role.setRoleCode(rs.getString("roleCode")); _role.setRoleName(rs.getString("roleName")); roleList.add(_role); } BaseDao.close(rs,pstat,null); } return roleList; }
-
RoleService
public List<Role> getRoleList();
-
RoleServicelmpI
//获取角色列表 public List<Role> getRoleList(){ Connection conn = null; List<Role> roleList = null; try { conn = BaseDao.getConnection(); roleList = roleDao.getRoleList(conn); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.close(null,null,conn); } return roleList; }
4.用户显示的Servlet
-
获取用户前端的数据(查询)
-
判断请求是否需要执行,看参数的值判断
-
为了实现分页,需要计算出当前页面和总页面,页面大小····
-
用户列表展示
-
返回前端
//重点和难点 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; //第一次走这个请求,一定是第一页,页面的大小固定的 int pageSize = 5;//可以吧这个写到配置文件中,方便后期修改 int currentPageNo = 1; if (queryusername==null){ queryusername = ""; } if (temp!=null && !temp.equals("")){ queryUserRole = Integer.parseInt(temp); //给查询赋值! 0,1,2,3 } 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 = ((int)(totalCount/pageSize))+1; //控制首页和尾页 //如果页面小于1,就显示第一页的东西 if (currentPageNo<1){ currentPageNo = 1; }else if (currentPageNo>totalPageCount){//当前页大于了最后一页 currentPageNo = totalPageCount; } //获取用户列表前端展示 userList = userService.getUserList(queryusername,queryUserRole,currentPageNo,pageSize); if (userList==null){ System.out.println("你的程序出错啦!"); } req.setAttribute("userList",userList); RoleServicelmpI roleService = new RoleServicelmpI(); 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(); } }