1.创建工程导入jar包
2.创建pojo包
package com.openlab.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class User {
private Integer id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
private String phone;
private String address;
private Integer userRole;
private Integer createdBy;
private Date creationDate;
private Integer modifyBy;
private Date modifyDate;
private String idPicPath;
private String workPicPath;
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public String getIdPicPath() {
return idPicPath;
}
public void setIdPicPath(String idPicPath) {
this.idPicPath = idPicPath;
}
public String getWorkPicPath() {
return workPicPath;
}
public void setWorkPicPath(String workPicPath) {
this.workPicPath = workPicPath;
}
}
package com.openlab.pojo;
public class Role {
private Integer id;
private String roleName;
private String roleCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
}
3.创建并配置applicationContext.xml和springMVC.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.openlab.dao.impl"></context:component-scan>
<context:component-scan base-package="com.openlab.service.impl"></context:component-scan>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:resources location="/statics/" mapping="s/**"></mvc:resources>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.openlab.controller"></context:component-scan>
</beans>
4.创建dao包
package com.openlab.dao;
import com.openlab.pojo.Role;
import java.util.List;
public interface RoleDao {
List<Role> getRoleList();
}
package com.openlab.dao;
import com.openlab.pojo.User;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
public interface UserDao {
User selectByUserCodeAndPassword(String userCode, String password);
List<User> getUserList(String userName, int roleId);
User getUserById(String id);
public int updateByUserId(String id, String userName, String userPassword, int gender, Date birthday, String phone, String address);
int add(User user);
int deleteById(String id);
}
5.创建dao.impl包
package com.openlab.dao.impl;
import com.openlab.dao.RoleDao;
import com.openlab.pojo.Role;
import com.openlab.utils.JDBCUtils;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
@Repository
public class RoleDaoImpl implements RoleDao {
@Override
public List<Role> getRoleList() {
Connection conn= JDBCUtils.getConnection();
Statement st=null;
ResultSet rs=null;
Role role=null;
String sql="select * from smbms_role";
List<Role> list=new ArrayList();
try {
st=conn.createStatement();
rs=st.executeQuery(sql);
while(rs.next()){
role=new Role();
role.setId(rs.getInt("id"));
role.setRoleCode(rs.getString("roleCode"));
role.setRoleName(rs.getString("roleName"));
list.add(role);
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,rs,st);
return list;
}
}
package com.openlab.dao.impl;
import com.openlab.dao.UserDao;
import com.openlab.pojo.User;
import com.openlab.utils.JDBCUtils;
import org.springframework.stereotype.Repository;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
@Override
public User selectByUserCodeAndPassword(String userCode, String password) {
String sql = "select * from smbms_user where userCode = ? and userPassword = ?";
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,userCode);
preparedStatement.setString(2,password);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
user = new User();
user.setUserName(resultSet.getString("userName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(connection,resultSet,preparedStatement);
return user;
}
@Override
public List<User> getUserList(String userName, int roleId) {
Connection conn=JDBCUtils.getConnection();
Statement st=null;
ResultSet rs = null;
StringBuffer sql=new StringBuffer("select u.*,r.roleName from smbms_user u,smbms_role r where 1=1");
if(userName!=null &&userName!=""){
sql.append(" and u.userName like '%"+userName+"%'");
}
if(new Integer(roleId)!=null){
if(roleId>0){
sql.append(" and u.userRole="+roleId);
}
}
sql.append(" and u.userRole=r.id order by creationDate desc");
List<User> list=new ArrayList();
try {
st=conn.createStatement();
rs=st.executeQuery(sql.toString());
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.setAddress(rs.getString("address"));
user.setRoleName(rs.getString("roleName"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,rs,st);
return list;
}
@Override
public User getUserById(String id) {
Connection conn=JDBCUtils.getConnection();
Statement st=null;
ResultSet rs=null;
User user=null;
String sbf=new String("select u.* from smbms_user u where u.id="+id);
try {
st=conn.createStatement();
rs=st.executeQuery(sbf);
while(rs.next()){
user=new User();
user.setId(rs.getInt("id"));
user.setUserCode(rs.getString("userCode"));
user.setUserPassword(rs.getString("userPassword"));
user.setUserName(rs.getString("userName"));
user.setGender(rs.getInt("gender"));
user.setBirthday(rs.getDate("birthday"));
user.setPhone(rs.getString("phone"));
user.setAddress(rs.getString("address"));
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,rs, st);
return user;
}
@Override
public int updateByUserId(String id, String userName, String userPassword,
int gender, Date birthday, String phone, String address) {
Connection conn=JDBCUtils.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
String sql=new String("update smbms_user u set userName=?,userPassword=?,gender=?,birthday=?,phone=?,address=? where u.id=?");
int result=0;
try {
pst=conn.prepareStatement(sql);
pst.setString(1, userName);
pst.setString(2, userPassword);
pst.setInt(3, gender);
pst.setDate(4, new java.sql.Date(birthday.getTime()));
pst.setString(5, phone);
pst.setString(6, address);
pst.setInt(7, Integer.parseInt(id));
result=pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,rs, pst);
return result;
}
@Override
public int add(User user) {
Connection conn=JDBCUtils.getConnection();
Statement st=null;
int result=0;
try {
String sql = "insert into smbms_user(userCode,userName,userPassword,gender,birthday,phone,address) values (\""+
user.getUserCode()+"\",\""+user.getUserName()+"\",\""+user.getUserPassword()+"\","+user.getGender()+",\""+new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday())+"\",\""+user.getPhone()+"\",\""+user.getAddress()+"\")";
System.out.println(sql);
st=conn.createStatement();
result=st.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,null,st);
return result;
}
@Override
public int deleteById(String id) {
Connection conn=JDBCUtils.getConnection();
Statement st=null;
int result=0;
String sql="delete from smbms_user where id="+id ;
try {
st=conn.createStatement();
result=st.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,null,st);
return result;
}
}
6.创建service包
package com.openlab.service;
import com.openlab.pojo.Role;
import java.util.List;
public interface RoleService {
List<Role> findRoleList();
}
package com.openlab.service;
import com.openlab.pojo.User;
import java.util.Date;
import java.util.List;
public interface UserService {
User login(String userCode, String password);
public List<User> findUserList(String userName, int roleId);
public User findUserById(String id);
public int updateByUserId(String id, String userName, String userPassword, int gender, Date birthday, String phone, String address);
public int save(String userCode, String userName, String userPassword, int gender, Date birthday, String phone, String address);
public int deleteById(String id);
}
7.创建service.impl包
package com.openlab.service.impl;
import com.openlab.dao.RoleDao;
import com.openlab.pojo.Role;
import com.openlab.service.RoleService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
@Resource
private RoleDao roleDao;
public RoleDao getRoleDao() {
return roleDao;
}
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public List<Role> findRoleList() {
return roleDao.getRoleList();
}
}
package com.openlab.service.impl;
import com.openlab.dao.UserDao;
import com.openlab.pojo.User;
import com.openlab.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User login(String userCode, String password) {
return userDao.selectByUserCodeAndPassword(userCode,password);
}
@Override
public List<User> findUserList(String userName, int roleId) {
return userDao.getUserList(userName, roleId);
}
@Override
public User findUserById(String id) {
return userDao.getUserById(id);
}
@Override
public int updateByUserId(String id, String userName, String userPassword,
int gender, Date birthday, String phone, String address) {
return userDao.updateByUserId(id, userName, userPassword, gender, birthday, phone, address);
}
@Override
public int save(String userCode, String userName, String userPassword, int gender, Date birthday, String phone, String address) {
User user = new User();
user.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setGender(gender);
user.setBirthday(birthday);
user.setPhone(phone);
user.setAddress(address);
return userDao.add(user);
}
@Override
public int deleteById(String id) {
return userDao.deleteById(id);
}
}
8.创建controller包
package com.openlab.controller;
import com.openlab.pojo.Role;
import com.openlab.pojo.User;
import com.openlab.service.RoleService;
import com.openlab.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private RoleService roleService;
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping(value = "/doLogin",method = RequestMethod.POST )
public String doLogin(String userCode, String password, HttpServletRequest request, HttpSession session){
User user = userService.login(userCode, password);
if(user!=null){
session.setAttribute("user",user);
return "redirect:/user/check";
}else {
throw new RuntimeException("用户名或密码错误");
}
}
@RequestMapping("/check")
public String main(HttpSession session){
if(session.getAttribute("user")==null){
return "redirect:/user/login";
}else {
return "redirect:/main.jsp";
}
}
@RequestMapping("/logout")
public String logout(HttpSession session){
session.removeAttribute("user");
return "redirect:/user/login";
}
@RequestMapping(value="/findUserList.html" )
public String findUserList(@RequestParam(value="userName",required=false)String userName, @RequestParam(value="roleId",required=false,defaultValue="0")int roleId, Model model){
List<User> list=userService.findUserList(userName, roleId);
List<Role> roleList=roleService.findRoleList();
model.addAttribute("userList",list);
model.addAttribute("queryUserName",userName);
model.addAttribute("queryroleId",roleId);
model.addAttribute("roleList",roleList);
System.out.println(list.size());
return "userList";
}
@RequestMapping(value="/getUserById.html/{uid}")
public String findByUserId(@PathVariable(value="uid") String id,Model model){
User user=userService.findUserById(id);
model.addAttribute("u",user);
return "userInfo";
}
@RequestMapping(value="/updateUserById.html/{id}")
public String updateUserById(@PathVariable(value="id") String id, Model model){
User user=userService.findUserById(id);
model.addAttribute("u",user);
return "updateUser";
}
@RequestMapping(value="/update.html",method=RequestMethod.POST)
public String updateUser(User user,Model model){
System.out.println(user.getUserName());
int result=userService.updateByUserId(user.getId().toString(), user.getUserName(), user.getUserPassword(), user.getGender(), user.getBirthday(), user.getPhone(), user.getAddress());
if(result>0){
return "redirect:/user/findUserList.html";
}else{
model.addAttribute("error","修改失败,请重新操作....");
return "updateUser";
}
}
//删除
@RequestMapping("/delete.html/{id}")
public String deleteUser(@PathVariable(value="id")String id, HttpServletResponse response){
int result = userService.deleteById(id);
if(result>0){
return "redirect:/user/findUserList.html";
}else {
try {
response.getWriter().println("<script language='javascript'>alert('发生异常错误,删除失败');</script>");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/user/findUserList.html";
}
}
//添加
@RequestMapping(value="/add.html",method=RequestMethod.POST)
public String addUser(String userCode, String userName, String userPassword, int gender, String birthday, String phone, String address, Model model){
Date birthdaydate = null;
try {
birthdaydate = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
} catch (ParseException e) {
model.addAttribute("error","日期不符合格式,请重新操作....");
return "addUser";
}
int save = userService.save(userCode,userName,userPassword,gender,birthdaydate,phone,address);
if(save>0){
return "redirect:/user/findUserList.html";
}else{
model.addAttribute("error","添加失败,请重新操作....");
return "addUser";
}
}
}
9.配置web.xml文件
10在原web根目录下新创建addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Title</title>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/user/add.html" method="post">
<table width="100%" height="100%" align="center">
<tr>
<td>账号:</td>
<td><input type="text" name="userCode"/></td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="userPassword"/></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="gender" value="1" />男
<input type="radio" name="gender" value="2"/>女
</td>
</tr>
<tr>
<td>生日:</td>
<td><input type="text" name="birthday"/></td>
</tr>
<tr>
<td>联系电话:</td>
<td><input type="text" name="phone" /></td>
</tr>
<tr>
<td>联系地址:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td style="color: red">${error}</td><td></td>
</tr>
<tr>
<td><input type="submit" value="添加" /></td>
<td><input type="reset" value="取消"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
11.修改userList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userList.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div>
<form
action="${pageContext.request.contextPath}/user/findUserList.html" method="post">
<p>
姓名:<input type="text" name="userName" value="${queryUserName}" />
用户角色:<select name="roleId">
<option value="0">--请选择--</option>
<c:forEach var="role" items="${roleList}">
<option value="${role.id}"
<c:if test="${role.id==queryroleId}">selected="selected"</c:if>>
${role.roleName}</option>
</c:forEach>
</select> <input type="submit" value="查询" /> <input type="reset" value="取消" />
</p>
</form>
<!--增加添加用户 -->
<div style="float: right;"><a href="addUser.jsp" >新增用户</a></div>
</div>
<!-- 遍历所有的用户 -->
<div>
<table width="100%" height="100%">
<tr>
<th width="10%">用户账号</th>
<th width="20%">用户名称</th>
<th width="10%">性别</th>
<th width="10%">电话</th>
<th width="10%">地址</th>
<th width="10%">用户角色</th>
<th width="30%">操作</th>
</tr>
<c:forEach var="user" items="${userList}" varStatus="status">
<tr>
<td>${user.userCode}</td>
<td>${user.userName}</td>
<td>
<c:if test="${user.gender==1}">男</c:if>
<c:if test="${user.gender==2}">女</c:if>
</td>
<td>${user.phone}</td>
<td>${user.address}</td>
<td>${user.roleName}</td>
<td>
<a href="${pageContext.request.contextPath}/user/getUserById.html/${user.id}"><img src="sta/images/read.png" title="查看" /></a>
<a href="${pageContext.request.contextPath}/user/updateUserById.html/${user.id}"><img src="sta/images/xiugai.png" title="修改" /></a>
<a href="${pageContext.request.contextPath}/user/delete.html/${user.id}"><img src="sta/images/schu.png" title="删除" /></a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
12.测试