创建mavenWeb项目
spring依赖、spring-web依赖、spring-webmvc依赖、spring-test、junit依赖
servlet依赖、jsp依赖、jstl、standard依赖
jackson的core和databind和annotations依赖、fastjson依赖、
文件上传的commons-fileupload和commons-io依赖
日志commons-logging、slf4j-log4j12、log4j依赖
mysql依赖、c3p0依赖、druid依赖、spring-jdbc依赖、spring-tx依赖
lombok依赖
4.0.0
org.example
SpringDemoModule
1.0-SNAPSHOT
war
org.springframework
spring-context
5.0.5.RELEASE
org.springframework
spring-web
5.0.5.RELEASE
org.springframework
spring-webmvc
5.0.5.RELEASE
org.springframework
spring-test
5.0.5.RELEASE
junit
junit
4.12
test
javax.servlet
javax.servlet-api
3.0.1
provided
javax.servlet.jsp
jsp-api
2.2
provided
jstl
jstl
1.2
taglibs
standard
1.1.2
com.fasterxml.jackson.core
jackson-core
2.10.3
com.fasterxml.jackson.core
jackson-databind
2.10.3
com.fasterxml.jackson.core
jackson-annotations
2.10.3
com.alibaba
fastjson
1.2.74
commons-fileupload
commons-fileupload
1.3.3
commons-io
commons-io
2.6
commons-logging
commons-logging
1.2
org.slf4j
slf4j-log4j12
1.7.7
log4j
log4j
1.2.17
mysql
mysql-connector-java
5.1.8
c3p0
c3p0
0.9.1.1
com.alibaba
druid
1.2.1
org.springframework
spring-jdbc
5.0.5.RELEASE
org.springframework
spring-tx
5.0.5.RELEASE
org.projectlombok
lombok
1.18.12
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
8080
/SpringDemoModule
配置web容器启动时创建spring上下文对象到servletContext
配置springMvc的post请求的中文乱码的编码过滤器
配置springMvc的前端控制器DispatcherServlet
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
CharacterEncodingFilter
/*
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
2
DispatcherServlet
/
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbc
jdbc.username=root
jdbc.password=root123
配置组件扫描、引入jdbc.properties、配置并接管c3p0数据源、配置并接管jdbcTemplate
public class DateConverter implements Converter {
@Override
public Date convert(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
配置controller的组件扫描、配置并接管视图解析器、配置上并接管日期转换器、配置并接管文件上传解析器、配置注解驱动(可对象转json)并配置日期转换器属性、配静态资源放行。
@Data//包括get、set、equals、hashCode、canEqual、toString、无参构造,没有有参构造
@NoArgsConstructor
@AllArgsConstructor
public class Role {
private Long id;
private String roleName;
private String roleDesc;
}
@Data//包括get、set、equals、hashCode、canEqual、toString、无参构造,没有有参构造
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String email;
private Date birthday;
private Integer infoId;
private String englishTeacher;
//当前用户具备的角色
private List roles;
}
public interface RoleDao {
List selectAll();
void save(String roleName,String roleDesc);
List selectRolesByUid(Integer uid);
}
public interface UserDao {
List selectAll();
Long save(User user);
void saveUserRoleRelation(Integer uid,Integer [] roleIds);
void delUserRoleRel(Integer uid);
void delUser(Integer uid);
}
@Repository
public class RoleDaoImpl implements RoleDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper(Role.class));
}
public void save(String roleName,String roleDesc) {
jdbcTemplate.update("insert into sys_role(role_name,role_desc) values(?,?)", roleName, roleDesc);
}
@Override
public List selectRolesByUid(Integer uid) {
return jdbcTemplate.query("select * from sys_role where id in(select rid from sys_user_role where uid = ? )", new BeanPropertyRowMapper(Role.class),uid);
}
}
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper(User.class));
}
/*
* 主键返回
* */
@Override
public Long save(User user) {
//想要新增操作返回主键,不能使用下面这个新增操作的api
//jdbcTemplate.update("insert into sys_user(name,password,email,birthday,infoId,english_teacher) values(?,?,?,?,?,?)", user.getName(), user.getPassword(), user.getEmail(), user.getBirthday(), user.getInfoId(), user.getEnglishTeacher());、
String sql = "insert into sys_user(name,password,email,birthday,infoId,english_teacher) values(?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setDate(4, new java.sql.Date(user.getBirthday().getTime()));
ps.setInt(5, user.getInfoId());
ps.setString(6, user.getEnglishTeacher());
return ps;
}
}, keyHolder);
Long generatedId = keyHolder.getKey().longValue();
return generatedId;
}
@Override
public void saveUserRoleRelation(Integer uid, Integer[] roleIds) {
for (Integer rid:roleIds) {
jdbcTemplate.update("insert into sys_user_role(uid,rid) values(?,?)", uid, rid);
}
}
@Override
public void delUserRoleRel(Integer uid) {
jdbcTemplate.update("delete from sys_user_role where uid = ?",uid);
}
@Override
public void delUser(Integer uid) {
jdbcTemplate.update("delete from sys_user where id = ?",uid);
}
}
public interface RoleService {
List list();
void save(String roleName,String roleDesc);
}
public interface UserService {
List list();
List selectRolesByUid(Integer uid);
void save(User user,Integer [] roleIds);
void deleteUser(Integer userId);
}
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleDao roleDao;
@Override
public List list() {
return roleDao.selectAll();
}
@Override
public void save(String roleName,String roleDesc) {
roleDao.save(roleName,roleDesc);
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Override
public List list() {
return userDao.selectAll();
}
@Override
public List selectRolesByUid(Integer uid) {
return roleDao.selectRolesByUid(uid);
}
@Override
public void save(User user,Integer [] roleIds) {
Long uid = userDao.save(user);//经过主键返回处理了,返回的是新增数据的数据库生成的主键
userDao.saveUserRoleRelation(uid.intValue(),roleIds);
}
@Override
public void deleteUser(Integer userId) {
userDao.delUserRoleRel(userId);
userDao.delUser(userId);
}
}
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
private RoleService roleService;
@RequestMapping("/roleList")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView();
List roleList = roleService.list();
modelAndView.addObject("roleList",roleList);//放到request域中
modelAndView.setViewName("role-list");//这里字符串会经过xml中配置的视图解析器处理,拼上前缀后缀,请求转发
return modelAndView;
}
@RequestMapping("/save")
public String save(HttpServletRequest req,String roleName,String roleDesc) {
try{
roleService.save(roleName,roleDesc);
return "redirect:/role/roleList";
}catch (Exception e){
e.printStackTrace();
req.setAttribute("error_msg","保存失败");
return "role-add";
}
}
}
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@RequestMapping("/userList")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView();
List userList = userService.list();
for (User user : userList) {
List roles = userService.selectRolesByUid(user.getId());
user.setRoles(roles);
}
modelAndView.addObject("userList", userList);//放到request域中
modelAndView.setViewName("user-list");//这里字符串会经过xml中配置的视图解析器处理,拼上前缀后缀,请求转发
return modelAndView;
}
@RequestMapping("/saveUI")
public String saveUI(HttpServletRequest request) {//用这种request加返回String返回页面的方式和上面的ModelAndView的方式均可,不过ModelAndView的方式在jsp页面有代码提示
List roleList = roleService.list();
request.setAttribute("roleList", roleList);
return "user-add";
}
@RequestMapping("/save")
public String save(User user, Integer[] roleIds, HttpServletRequest req) {//这里使用User对象封装参数,一个个的写入参也行。
try {
userService.save(user, roleIds);
return "redirect:/user/userList";
} catch (Exception e) {
e.printStackTrace();
req.setAttribute("error_msg", "保存失败");
return "user-add";
}
}
@RequestMapping("/del/{userId}")/*由于客户端使用的restFul风格传参,所以controller接收restful风格参水*/
public String del(@PathVariable("userId") Integer uid) {
userService.deleteUser(uid);
return "redirect:/user/userList";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
index
首页
用户管理
角色管理
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
RoleList
新增
刷新
选中
id
角色名
角色描述
操作
${role.id}
${role.roleName}
${role.roleDesc}
删除
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
role-add
${error_msg}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
UserList
新增
刷新
选中
id
用户名
邮箱
生日
infoId
英语老师
具备角色
${user.id}
${user.name}
${user.email}
${user.birthday}
${user.infoId}
${user.englishTeacher}
${role.roleName}
删除
<%--javascript:void(0)让该超链接不跳转到任何地方,而鼠标移上去有小手--%>
<%--onclick点击时执行的方法--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
user-add
${error_msg}
http://localhost:8080//SpringDemoModule/jsp/index.jsp