发布于2021-05-30 12:24 阅读(1472) 评论(0) 点赞(9) 收藏(1)
搭建一个maven web项目
配置Tomcat
测试项目环境是否能跑起来
导入jar包(jsp、servlet、mysql驱动、jstl、standard…)
创建项目包结构
编写实体类(ORM映射)
编写基础公共类
数据库配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=true
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 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, PreparedStatement preparedStatement, ResultSet resultSet, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject占位符从1开始,但是数据从0开始
preparedStatement.setObject(i+1,params[i]);
}
resultSet = preparedStatement.executeQuery();
return resultSet;
}
//编写增、删、改公共方法
public static int execute(Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject占位符从1开始,但是数据从0开始
preparedStatement.setObject(i+1,params[i]);
}
int updateRows = preparedStatement.executeUpdate();
return updateRows;
}
//释放资源
public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
boolean flag = true;
if (resultSet != null){
try {
resultSet.close();
//gc回收
resultSet = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (preparedStatement != null){
try {
preparedStatement.close();
//gc回收
preparedStatement = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection != null){
try {
connection.close();
//gc回收
connection = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
编写字符编码过滤器
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
导入静态资源(css,js,image…)
编写前端页面
设置主页
<!--设置首页-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
编写dao层用户登录接口(UserDao)
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode,String userPassword) throws SQLException;
编写dao接口的实现类(UserDaoImpl)
//得到要登录的用户
public User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
if (connection != null){
String sql = "select * from smbms_user where userCode=? and userPassword=?";
Object[] params = {userCode,userPassword};
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.closeResource(null,preparedStatement,resultSet);
}
return user;
}
业务层接口(UserService)
//用户登录
public User login(String userCode,String userPassword);
业务层实现类(UserServiceImpl)
//业务层都会调用dao层
private UserDao userDao;
public UserServiceImpl(){
userDao = new UserDaoImpl();
}
public User login(String userCode, String userPassword) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
//通过业务层调用对应的具体的数据库操作层
user = userDao.getLoginUser(connection,userCode,userPassword);
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
编写Servlet
//控制层调用业务层
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名和密码
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
//和数据库中的密码进行对比,调用业务层
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);
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);
}
注册登录Servlet
<!--登录-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.java.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
测试访问
注销功能:移除Session,返回登录页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
注册登出Servlet
<!--登出-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.java.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截优化(过滤器)
编写过滤器
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(request.getContextPath()+"/error.jsp");
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
注册过滤器
<!--用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.java.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
导入前端素材
编写UserDao接口
public int updatePwd(Connection connection, int id, String userPassword)throws SQLException;
编写UserDao接口实现类
//修改当前用户密码
public int updatePwd(Connection connection, int id, String userPassword) throws SQLException {
PreparedStatement preparedStatement = null;
int i = 0;
if (connection != null) {
String sql = "update smbms_user set userPassword=? where id=?";
Object[] params = {userPassword, id};
i = BaseDao.execute(connection, preparedStatement, sql, params);
BaseDao.closeResource(connection, preparedStatement, null);
}
return i;
}
编写UserService接口
public boolean updatePwd(int id, String userPassword);
编写UserService接口实现类
public boolean updatePwd(int id, String userPassword) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (userDao.updatePwd(connection,id,userPassword)>0){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
实现复用,需要提取出方法
//实现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);
}else if(method.equals("pwdmodify")&&method != null){
this.pwdModify(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
//从Session中拿到ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
if (o != null && newpassword != null &&newpassword.length()!=0){
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User)o).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验证旧密码是否正确
oldpassword.on("blur",function(){
$.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 + " 原密码输入不正确",false);
}else if(data.result == "sessionerror"){//当前用户session过期,请重新登录
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 当前用户session过期,请重新登录",false);
}else if(data.result == "error"){//旧密码输入为空
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请输入旧密码",false);
}
},
error:function(data){
//请求出错
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请求错误",false);
}
});
导入阿里巴巴的fastjson:Json工具,转换格式
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
编写后端代码
//验证旧密码,Session中
public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
//结果集
Map<String,String> resultMap = new HashMap<String, String>();
if (o == null){ //Session过期
resultMap.put("result","sessionerror");
}else if (oldpassword == null || oldpassword.length()==0){
resultMap.put("result","error");
}else{
String userPassword = ((User) o).getUserPassword();
if (oldpassword.equals(userPassword)){
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();
}
}
思路:
UserDao
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection, String username, int userRole)throws SQLException;
UserDaoImpl
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = 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();
resultSet = BaseDao.execute(connection, preparedStatement,resultSet, sql.toString(), objects);
if (resultSet.next()){
count = resultSet.getInt("count");//从结果中获取最终的数量
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return count;
}
UserService
//根据用户名或者角色查询用户总数
public int getUserCount(String username, int userRole);
UserServiceImpl
public int getUserCount(String username, int userRole) {
Connection connection = null;
int count = 0;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, username, userRole);
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return count;
}
UserDao
//获取用户列表
public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException;
UserDaoImpl
//获取用户列表
public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int count = 0;
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");
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
}
sql.append(" order by creationDate DESC limit ?,?");
currentPageNo = (currentPageNo-1)*pageSize;
list.add(currentPageNo);
list.add(pageSize);
//将list转换为数组
Object[] objects = list.toArray();
resultSet = BaseDao.execute(connection, preparedStatement,resultSet, sql.toString(), objects);
if (resultSet.next()){
User _user = new User();
_user.setId(resultSet.getInt("id"));
_user.setUserCode(resultSet.getString("userCode"));
_user.setUserName(resultSet.getString("userName"));
_user.setGender(resultSet.getInt("gender"));
_user.setBirthday(resultSet.getDate("birthday"));
_user.setPhone(resultSet.getString("phone"));
_user.setUserRole(resultSet.getInt("userRole"));
_user.setUserRoleName(resultSet.getString("userRoleName"));
userList.add(_user);
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return userList;
}
UserService
//获取用户列表
public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize);
UserServiceImpl
//获取用户列表
public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, username,userRole,currentPageNo,pageSize);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return userList;
}
为了职责统一,可以把角色的操作单独放在一个包中,和pojo对应
RoleDao
//获取角色列表
public List<Role> getRoleList(Connection connection) throws SQLException;
RoleDaoImpl
//获取角色列表
public List<Role> getRoleList(Connection connection) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Role> roleList = new ArrayList<Role>();
if(connection != null){
String sql = "select * from smbms_role";
Object[] params = {};
resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);
while (resultSet.next()){
Role _role = new Role();
_role.setId(resultSet.getInt("id"));
_role.setRoleCode(resultSet.getString("roleCode"));
_role.setRoleName(resultSet.getString("roleName"));
roleList.add(_role);
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return roleList;
}
RoleService
//获取角色列表
public List<Role> getRoleList();
RoleServiceImpl
public List<Role> getRoleList() {
Connection connection = null;
List<Role> roleList = null;
try {
connection = BaseDao.getConnection();
roleList = roleDao.getRoleList(connection);
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return roleList;
}
获取用户前端的数据
判断请求是否需要执行,看参数的值判断
为了实现分页,需要算出当前页面、总页面和页面大小
用户列表展示
返回前端
//代码复用
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
....
else if (method.equals("query")&&method != null){
this.query(req,resp);
}
}
//用户列表
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 currentPageNo = 1;
if (queryUserName == null){
queryUserName = "";
}
if (temp != null && !temp.equals("")){
queryUserRole = Integer.parseInt(temp);
}
if (pageIndex != null){
currentPageNo = Integer.parseInt(pageIndex);
}
//获取用户的总数(分页)
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
//总页数支持
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(Constants.pageSize);
pageSupport.setTotalCount(totalCount);
int totalPageCount = pageSupport.getTotalPageCount();
//控制首页和尾页
//如果页面要小于1,就显示第一页的内容
if (totalPageCount < 1){
currentPageNo = 1;
}else if (currentPageNo > totalPageCount){ //当前页大于最后一页
currentPageNo = totalPageCount;
}
//获取用户列表展示
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, Constants.pageSize);
req.setAttribute("userList",userList);
RoleServiceImpl roleService = new RoleServiceImpl();
List<Role> roleList = roleService.getRoleList();
req.setAttribute("roleList",roleList);
req.setAttribute("totalPageCount",totalPageCount);
req.setAttribute("totalCount",totalCount);
req.setAttribute("currentPageNo",currentPageNo);
//返回前端
try {
req.getRequestDispatcher("userlist.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
原文链接:https://blog.csdn.net/TvTToT/article/details/117261032
作者:西小口到了吗
链接:http://www.qianduanheidong.com/blog/article/116075/0e7d4ffed3fb16ed58a4/
来源:前端黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 前端黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-3
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!