SMBMS
项目搭建准备工作
-
搭建一个maven,web工程 -
配置tomcat -
测试项目能不能跑起来 -
导入jar包 jsp,servlet,mysql驱动,jstl,stand… -
创建项目包结构
-
编写实体类 ORM映射:表-类映射 -
编写基础公共类
-
数据库配置文件 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8
username=root
password=root
-
编写数据库的公共类 package com.kuang.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() throws Exception{
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static ResultSet execute(Connection connection, String sql,Object[] params, ResultSet rs, PreparedStatement preparedStatement)throws Exception{
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i <params.length; i++) {
preparedStatement.setObject(i+1,params[i]);
}
rs = preparedStatement.executeQuery();
return rs;
}
public static int execute(Connection connection, String sql,Object[] params, PreparedStatement preparedStatement)throws Exception{
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i <params.length; i++) {
preparedStatement.setObject(i+1,params[i]);
}
int update = preparedStatement.executeUpdate();
return update;
}
public static void closeResourc(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
if (resultSet!=null&&preparedStatement!=null&&connection!=null){
resultSet.close();
preparedStatement.close();
connection.close();
}
}
}
-
编写字符编码过滤器 package com.kuang.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 servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
记得在web.xml中形成映射 -
导入静态资源
登录功能实现
-
编写前端页面 -
设置首页 <welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
-
编写dao层用户登录的接口 public interface UserDao {
public User getLoginUser(Connection connection,String userCode) throws Exception;
}
-
编写dao层用户登录的实现类 package com.kuang.dao.User;
import com.kuang.dao.BaseDao;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserDaoImpl implements UserDao{
@Override
public User getLoginUser(Connection connection, String userCode) throws Exception{
PreparedStatement preparedStatement =null;
ResultSet resultSet=null;
User user=null;
String sql = "select * from smbms_user where userCode = ?";
Object[] params={userCode};
resultSet=BaseDao.execute(connection,sql,params,resultSet,preparedStatement);
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.closeResourc(connection,preparedStatement,resultSet);
return user;
}
}
-
业务层接口
public User login(String userCode,String password);
-
业务层实现类 package com.kuang.service.user;
import com.kuang.dao.BaseDao;
import com.kuang.dao.User.UserDao;
import com.kuang.dao.User.UserDaoImpl;
import com.kuang.pojo.User;
import org.junit.Test;
import java.sql.Connection;
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);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
@Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
User admin = userService.login("admin", "12");
System.out.println(admin.getUserPassword());
}
}
-
编写servlet package com.kuang.servlet.user;
import com.kuang.pojo.User;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.util.Constansts;
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("Jin");
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);
if (user!=null){
req.getSession().setAttribute(Constansts.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 {
doPost(req, resp);
}
}
-
注册servlet <servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.kuang.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 {
req.getSession().removeAttribute(Constansts.USER_SESSION);
resp.sendRedirect("/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.kuang.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截优化
编写一个过滤器,并注册
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(Constansts.USER_SESSION);
if (user==null){
response.sendRedirect("/error.jsp");
}
else{
Chain.doFilter(req,resp);
}
}
@Override
public void destroy() {
}
}
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.kuang.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,int password) throws Exception;
-
UserDao接口实现类 public int updatePwd(Connection connection, int id, int password) throws Exception {
PreparedStatement pstm = null;
String sql="update smbms_user set userPassword = ? where id=?";
Object[] params={password,id};
int execute = BaseDao.execute(connection, sql, params, pstm);
return execute;
}
-
UserService public boolean updatePwd( int id, int password);
-
UserService实现类 @Override
public boolean updatePwd(int id, int password) {
Connection connection=null;
boolean flag=false;
try {
connection=BaseDao.getConnection();
if (userDao.updatePwd(connection,id,password)>0){
flag=true;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
-
Servlet记得实现复用,需要提取出方法 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if (method!=null&&method.equals("savepwd")){
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){
User user = (User)req.getSession().getAttribute(Constansts.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
if (user!=null&& !StringUtils.isNullOrEmpty(newpassword)){
UserServiceImpl userService = new UserServiceImpl();
flag=userService.updatePwd(user.getId(),newpassword);
if (flag){
req.setAttribute("message","修改密码成功,请退出,使用新密码登录");
req.getSession().removeAttribute(Constansts.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 <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
-
后台代码修改 public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
User user = (User)req.getSession().getAttribute(Constansts.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
if (user!=null&& !StringUtils.isNullOrEmpty(newpassword)){
UserServiceImpl userService = new UserServiceImpl();
flag=userService.updatePwd(user.getId(),newpassword);
if (flag){
req.setAttribute("message","修改密码成功,请退出,使用新密码登录");
req.getSession().removeAttribute(Constansts.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();
}
}
-
测试
用户管理实现
思路:
-
导入分页的工具类 -
用户列表页面导入 userlist.jsp
1.获取用户数量
-
UserDao public int getUserCount(Connection connection,String username,int userRole) throws Exception;
-
UserDaoImpl @Override
public int getUserCount(Connection connection, String username, int userRole) throws Exception {
PreparedStatement pstm=null;
ResultSet rs=null;
int count = 0;
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("add u.username like ?");
list.add("%"+username+"%");
}if (userRole>0){
sql.append("and u.userRole =?");
list.add(userRole);
}
Object[] params = list.toArray();
rs = BaseDao.execute(connection, sql.toString(), params, rs, pstm);
if (rs.next()){
count=rs.getInt("count");
}
return count;
}
-
UserService public int getUserCount(String username,int userRole);
-
UserServiceImpl @Override
public int getUserCount(String username, int userRole) {
Connection connection=null;
int count = 0;
try {
connection = BaseDao.getConnection();
count=userDao.getUserCount(connection,username,userRole);
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
2.获取用户列表
- userdao
- userdaoImpl
- userService
- userServiceImpl
3.获取角色操作
为了我们职责统一,可以把角色的操作单独放在一个包中,和POJO类对应
- roledao…与上面等同
4.用户显示的Servlet
- 获取用户前端的数据(查询)
- 判断请求是否需要执行,看参数的值判断
- 为了实现分页,需要计算出当前页面和总页面,页面大小
- 用户列表展示
|