smbms

1、项目准备工作

1、搭建一个maven项目

2、配置tomcat

3、测试项目

4、导入依赖jar包

5、创建包结构

dao filter pojo service servlet util

6、编写实体类

ORM映射:表–类映射

7、编写基础公共类

​ 1、数据库配置文件 db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306?userUnicode=true&characterEncoding=utf-8
username=root
password=root

​ 2、编写数据库的公共类(增删改查)


import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.sql.Connection;
//import com.mysql.jdbc.Connection;

//操作数据库的公共类
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) {
			// TODO Auto-generated catch block
			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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
//	编写查询公共类:
	public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultset,PreparedStatement preparestatement) throws SQLException {
//		预编译的sql在后面直接执行就可以了
		preparestatement = connection.prepareStatement(sql);
		for(int i=0;i<params.length;i++) {
//			setObject:占位符从1开始 但是数组从0开始
			preparestatement.setObject(i+1, params[i]);
			
		}
		ResultSet resultSet = preparestatement.executeQuery(sql);
		
		return resultSet;	
	}
//	编写增删改公共方法
//	更新
	public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparestatement) throws SQLException {
		preparestatement = connection.prepareStatement(sql);
		for(int i=0;i<params.length;i++) {
//			setObject:占位符从1开始 但是数组从0开始
			preparestatement.setObject(i+1, params[i]);
			
		}
		int updateRows = preparestatement.executeUpdate();
		
		return updateRows;	
	}
//	释放资源
public static boolean closeResource(Connection connection,ResultSet resultset,PreparedStatement preparestatement) {
	boolean flag = true;
	if(resultset != null) {
		try {
			resultset.close();
			resultset=null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag = false;
		}
	}
	if(connection != null) {
		try {
			connection.close();
			connection=null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag = false;
		}
	}
	if(preparestatement != null) {
		try {
			preparestatement.close();
			preparestatement=null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag = false;
		}
	}
	
	return flag;
		
	}
}

eclipse 快速new对象:Ctrl+2,L

​ 3、编写字符编码过滤器

public class CharacterEncordingFiter implements Filter{

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		chain.doFilter(request, response);
	
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
# web.xml
<filter>
	<filter-name>ChracterEncordingFilter</filter-name>
	<filter-class>com.lu.filter.CharacterEncordingFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>ChracterEncordingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

8、导入静态资源

2、登录功能实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0RHtst6C-1628165269210)(D:\Java学习\java–狂神说\smbms.png)]

1、编写前端页面

2、设置欢迎页面

<!-- 设置欢迎页面 -->
<welcome-file-list>
	<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 设置欢迎页面 -->

3、编写到层登录用户登录的接口

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[] params= {userCode};
			rs = BaseDao.execute(connection,pstm,rs,sql,params);
			if(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setUserCode(rs.getString("userCode"));
				user.setUserPassword(rs.getString("userPassword"));
				user.setGender(rs.getInt("gender"));
				user.setBrithday(rs.getDate("birthday"));
				user.setPhone(rs.getString("phone"));
				user.setUserRole(rs.getInt("userRole"));
				user.setCreateBy(rs.getInt("createBy"));
				user.setCreationDate(rs.getDate("creationDate"));
				user.setModifyBy(rs.getInt("modifyBy"));
				user.setModifyDate(rs.getTimestamp("modifyDate"));	
			}
			BaseDao.closeResource(null,rs,pstm);
		}
		return user;
jdbc:mysql://localhost:3306/user_database	}

url = jdbc:mysql://localhost:3306/smbms?useSSL=true&userUnicode=true&characterEncoding=utf-8

5、业务层接口

public user login(Sytinr usercode,String password)

//			连接数据库
			connection = BaseDao.getConnection();
//			获得登录的用户
			user = userDao.getLoginUser(connection, userCode);

6、业务层实现类



import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Test;

import com.lu.dao.BaseDao;
import com.lu.dao.user.UserDao;
import com.lu.dao.user.UserDaoimpl;
import com.lu.pojo.User;

public class UserServiceImpl implements UserService{
//业务层都会调用dao层  所以要引入Dao层
	private UserDao userDao;
//	一旦 new出来UserServiceImpl时  UserDaoimpl就被实例化了  
	public UserServiceImpl() {
		userDao = new UserDaoimpl();
	}
	
	

	public User login(String userCode, String password) {
		Connection connection =null;
		User user = null;
		
		try {

//			通过业务层调用对应的具体的数据库操作
//			连接数据库
			connection = BaseDao.getConnection();
//			获得登录的用户
			user = userDao.getLoginUser(connection, userCode);
			

​```java
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		BaseDao.closeResource(connection, null, null);
	}
	return user;
}

//	@Test
//	public void test() {
//		UserServiceImpl userService = new UserServiceImpl();
//		User admin = userService.login("admin","123456hhh");
//		System.out.print(admin.getUserPassword());
//	}
}

7、编写servlet

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		获取用户名和密码
		String usercode = req.getParameter("userCode");
		String password = req.getParameter("userPassword");
//		调用业务层  和数据库账户密码对比
		UserServiceImpl userService = new UserServiceImpl();
		User user = userService.login(usercode, password);
		
		if(user != null) {
//			用户放到session
			System.out.print("user 不为空");
			req.getSession().setAttribute(Constants.USER_SESSION,user);
//			用户跳转
			resp.sendRedirect("jsp/frame.jsp");
		
		}
		else {
			req.setAttribute("error", "用户名或密码不正确");
			req.getRequestDispatcher("login.jsp").forward(req,resp);
		}
		
		
	}

8、注册servlet 与web表单提交对应

<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.lu.servlert.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>

9、测试访问

3、登录功能优化:

注销功能

思路:移出session 返回登录页面

public class LoginOutServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getSession().removeAttribute(Constants.USER_SESSION);
		resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录页面
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
	

}

注册XML

<!-- session注销 -->
<servlet>
<servlet-name>LoginOutServlet</servlet-name>
<servlet-class>com.lu.servlert.user.LoginOutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginOutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
<!-- session注销 -->
登录拦截优化

4、密码修改

1、导入前端素材

2、写项目自底向上

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;
	String sql = "updata smbms_user set userPassword = ? where id = ?";
	int excute = 0;
	if(connection != null) {
		Object params[]= {password,id};
		excute = BaseDao.executeUpdate(connection, pstm, sql, params);
		BaseDao.closeResource(null, null, pstm);
	}
	
	return excute;

5、userServise接口

public boolean updatePwd (int id,int pwd);

6、userservise实现类

public boolean updatePwd(int id, int pwd) {
	Connection connection = null;
	boolean flag=false;
	try {
		connection = BaseDao.getConnection();
		if(userDao.updatePwd(connection,id,pwd)>0) {
			flag=true;
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		BaseDao.closeResource(connection, null, null);
	}
	return flag;
	
}

7、实现复用。需要提取出方法

@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:

@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);
	}
}
验证旧密码
public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
		Object o = req.getSession().getAttribute(Constants.USER_SESSION);
		String oldpassword = req.getParameter("oldpassword");
		System.out.print(oldpassword);
//		万能的map:结果集
		Map<String,String> resultMap = new HashMap<String,String>();
		if(o==null) {//session失效了                        
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldpassword)) {
			resultMap.put("result", "error");
		}else {
			String userPassword =((User)o).getUserPassword();
			if(oldpassword.equals(userPassword)) {
				resultMap.put("result", "true");
			}else {
				resultMap.put("result", "false");
			}
			
		}
//		实质文本类型  返回一个json值
//		resp.setContentType("application/json");
//		获得
		try {
//			限定json格式
			resp.setContentType("application/json");
//			一个流 ajax返回
			PrintWriter writer = resp.getWriter();
//			JSONArrqy:阿里巴巴的json工具类  转换格式
			/*
			 resultMap = [ "" "" ]
			 Json={key,value}
			 */
			writer.write(JSONArray.toJSONString(resultMap));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

oop面向对象编程:三大特性:封装(属性私有 get/set 在set中限定一些不安全的情况 )、继承、多态

5、用户管理实现

1、导入分页的工具类(Pagesupport.java)

2、用户列表页面导入

​ userlist.jsp

​ rollpage

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 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+"%");
		    }
			if(userRole>0) {
				sql.append(" and u.userRole=?");
				list.add(userRole);
		    }
			Object[] params = list.toArray();
			
			System.out.print("UserDaoImpl==>"+sql.toString());
			rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
			if(rs.next()) {
				count=rs.getInt("count");//从结果集中获得最终数量
			}
			BaseDao.closeResource(null, rs, pstm);
		
		}
		
		return count;
		
	}

3、UserService

//	查询记录数
	public int getUserCount(String username,int userRole);

4、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) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	finally {
		BaseDao.closeResource(connection, null, null);
	}
	
	return count;	
}

2、获取用户列表

1、userDao

2、UserDaoImpl

3、UserService

4、UserServiceImpl

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐