title: javaweb项目-msbms
date: 2020-11-28 11:51:36
tags: javaweb
SMBMS
存在问题
乱码解决
- VM-OPTION
-Dfile.encoding=utf-8
- Js文件编码改为UTF-BOM
1、简介
数据库架构
如何搭建项目?
- jar
- maven
项目搭建
1.利用模板搭建maven-javaweb项目,注意maven配置信息需要重写
2.配置Tomcat
3.测试项目
4.导入jar包`servlet-api,jsp-api,mysql-connector-java,jstl-api,standard
5.创建包结构
6.编写实体类
ORM映射:表-类映射
7.编写基础公共类
- 数据库配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
- 编写数据库公共方法
package com.bzf.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("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 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开始,但是我们的数组从1开始
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{
for (int i = 0;i<params.length;i++){
//setObject(),占位符从1开始,但是我们的数组从1开始
preparedStatement.setObject(i+1,params[i]);
}
int updateRows = preparedStatement.executeUpdate();
return updateRows;
}
//释放资源
public static Boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
Boolean flag = true;
if (resultSet!=null){
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
if (preparedStatement!=null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
if (connection!=null){
try {
connection.close();
//GC回收
connection = null;
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
- 编写字符编码过滤器,注意在web.xml注册
8.导入静态资源,在webapp
3、登陆功能实现
1、编写前端页面
login.jsp,error.jsp
2、设置首页
<!--设置欢迎页面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3、编写Dao层得到用户登陆的接口
public interface UserDao {
// 得到需要登陆的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
}
4、编写dao接口的实现类
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[] param = {userCode};
rs = BaseDao.execute(connection, pstm, rs, sql, param);
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUserCode(rs.getString("userCode"));
user.setUserName(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;
}
5、编写业务层接口
public interface UserService {
//用户登陆
public User login(String userCode,String password) throws SQLException;
}
6、业务层实现类
public class UserServiceImpl implements UserService {
//业务层都会调用Dao层,所以我们要引入Dao层
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
public User login(String userCode, String password) throws SQLException {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
//通过业务层调用Dao层
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}
// 检验代码,发现即使密码错误也可以导出!
@Test
public void test() throws SQLException {
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login("admin", "12345sfsf67");
System.out.println(user.getUserPassword());
}
}
7、编写Servlet
ublic class Loginservlet extends HttpServlet {
//Servlet:控制层,调用业务层代码
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入loginServlet");
//获取前端用户名和密码
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
//和数据库中的密码进行对比,调用业务层
UserServiceImpl userService = new UserServiceImpl();
try {
User user = userService.login(userCode, userPassword);//已经把登陆的人从数据库中查询出来了
if (user!=null){
// 将用户的信息存放在session中
req.getSession().setAttribute(Constants.USER_SESSION,user);
//登陆成功后跳转到frame.jsp页面
resp.sendRedirect("jsp/frame.jsp");
} else { //没有查到该用户,无法登陆
//转发回登陆页面,顺带提示它,用户名或者密码错误
req.setAttribute("error","用户名或者密码不正确");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
8、注册Servlet
<!--Servlet-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.bzf.servlet.user.Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
登陆功能优化
注销功能
思路:移除Session,返回登陆页面
package com.bzf.servlet.user;
import com.bzf.util.Constants;
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 {
// 移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
// req.getSession().setMaxInactiveInterval(0);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册页面
<!--注销登陆-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.bzf.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登陆拦截优化
编写过滤器,针对jsp/*下的文件
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) resp;
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if (user==null){
response.sendRedirect(request.getContextPath()+"/error.jsp");
} else {
filterChain.doFilter(req,resp);
}
}
注册 web.xml
<!--注销登陆--> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.bzf.servlet.user.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping>
密码修改
-
导入前端素材
-
写项目,建议从底层向上写
3.UserDao接口
//修改密码 public int updatePwd(Connection connection,int id,int password) throws SQLException;
4.UserDao接口实现类
public int updatePwd(Connection connection, int id, int password) throws SQLException { PreparedStatement pstm =null; int execute = 0;//int execute = Integer.parseInt(null); if (connection!=null){//企业分工,万一前人,没有传过来connection String sql = "update smbms_user set `userPassword`= ? where id = ?"; Object[] params = {password,id}; execute = BaseDao.execute(connection, pstm, sql, params); BaseDao.closeResource(null,pstm,null); } return execute; }
5.userService
//修改密码 public boolean updatePwd( int id, int password) throws SQLException;
6.UserService实现类
public boolean updatePwd(int id, int password) throws SQLException { Connection connection = null; boolean flag = false; //修改密码 try { connection = BaseDao.getConnection(); if (userDao.updatePwd(connection,id,password)>0){ flag = true; } } catch (SQLException e) { e.printStackTrace(); } finally { BaseDao.closeResource(connection,null,null); return flag; } }
7.UserServlet 复用提取出方法
package com.bzf.servlet.user;import com.bzf.pojo.User;import com.bzf.service.user.UserServiceImpl;import com.bzf.util.Constants;import com.mysql.jdbc.StringUtils;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.sql.SQLException;//实现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 { doGet(req, resp); } public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从session里获取id Object user = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); if (user!=null && newpassword!=null){ UserServiceImpl userService = new UserServiceImpl(); try { boolean flag = userService.updatePwd(((User) user).getId(), newpassword); if (flag){ req.setAttribute("message","修改成功,请退出,使用新密码登陆"); //密码修改成功,移除当前session req.getSession().removeAttribute(Constants.USER_SESSION);//resp.sendRedirect("/login.do");是不可取的 } else { req.setAttribute("message","密码修改失败"); } } catch (SQLException e) { e.printStackTrace(); } req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } }}
8.注册
优化前端密码验证
用户管理实现
思路:
1.导入分页的工具类
2.用户列表页面导入
1、获取用户数量
1、UserDao
//查询用户总数 public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
2、UserDaoImpl
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 s where u.userRole=s.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 = ?");//index:1 list.add(userRole); } //怎么办list转化为数组 Object[] params = list.toArray(); System.out.println("UserDaoImpl->getUserCount:"+sql.toString());//输出完整的sql语句 rs = BaseDao.execute(connection,pstm,rs,sql.toString(),params); if(rs.next()){ count = rs.getInt("count"); } BaseDao.closeResource(null, pstm, rs); } return count; }
3、UserService
//查询记录数 public int getUserCount(String queryUserName, int queryUserRole) throws SQLException;
4、UserServiceImpl
public int getUserCount(String queryUserName, int queryUserRole) throws SQLException { // TODO Auto-generated method stub Connection connection = null; int count = 0; System.out.println("queryUserName ---- > " + queryUserName); System.out.println("queryUserRole ---- > " + queryUserRole); try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, queryUserName,queryUserRole); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return count;}
2、获取用户列表
3、获取角色操作
RoleDao
public interface RoleDao { public List<Role> getRoleList(Connection connection)throws Exception;}
RoleDaoImpl
public class RoleDaoImpl implements RoleDao{ public List<Role> getRoleList(Connection connection) throws Exception { PreparedStatement pstm = null; ResultSet rs = null; List<Role> roleList = new ArrayList<Role>(); if(connection != null){ String sql = "select * from smbms_role"; Object[] params = {}; rs = BaseDao.execute(connection, pstm, rs, sql, params); while(rs.next()){ Role _role = new Role(); _role.setId(rs.getInt("id")); _role.setRoleCode(rs.getString("roleCode")); _role.setRoleName(rs.getString("roleName")); roleList.add(_role); } BaseDao.closeResource(null, pstm, rs); } return roleList; }}
RoleService
public interface RoleService { public List<Role> getRoleList() throws SQLException; }
RoleServiceImpl
public class RoleServiceImpl implements RoleService{ private RoleDao roleDao; public RoleServiceImpl(){ roleDao = new RoleDaoImpl(); } public List<Role> getRoleList() throws SQLException { 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; } }
4、用户显示
- 获取用户的前端数据(查询)
- 判断请求是否需要执行,看参数的值判断
- 为了实现分页,需要计算当前页面和总页面,页面大小
- 返回用户列表展示
- 返回前端
private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { //查询用户列表 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; 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);}