(还存在需要完善的地方,例如新建新的用户,用户id不是从原表中进行提取)
Spring环境搭建步骤
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!--配置全局过滤的filter--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--③配置SpringMVC的前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--②全局初始化参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--①配置Spring监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
运行Tomcat ( localhost:8080/Spirng_war/ )
首先打开index.jsp页面,但因为写有如下代码,所以直接打开main.jsp
<%
response.sendRedirect(request.getContextPath()+"/pages/main.jsp");//默认打开main.jsp
%>
角色列表的展示
① 点击角色管理菜单发送请求到服务器端(修改角色管理菜单的url地址)
在main.jsp中发现aside.jsp(导航侧栏 )对其进行修改
<li><a href="${pageContext.request.contextPath}/pages/role/list"> <i class="fa fa-circle-o"></i> 角色管理</a></li>
domain —— Role
package com.zd.domain;
public class Role {
private Long id;
private String roleName;
private String roleDesc;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
② 创建RoleController
package com.zd.controller;
import com.zd.domain.Role;
import com.zd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@RequestMapping("/role")
@Controller
public class RoleController {
@Autowired
private RoleService roleService;
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
//设置模型
modelAndView.addObject("roleList",roleList);
//设置视图
modelAndView.setViewName("role-list");//展示列表的地址
System.out.println(roleList);
return modelAndView;
}
}
③ 创建RoleService
package com.zd.service;
import com.zd.domain.Role;
import java.util.List;
public interface RoleService {
public List<Role> list() ;
void save(Role role);
}
service —— impl —— RoleServiceImpl
package com.zd.service.impl;
import com.zd.dao.RoleDao;
import com.zd.domain.Role;
import com.zd.service.RoleService;
import java.util.List;
public class RoleServiceImpl implements RoleService {
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public List<Role> list() {
List<Role> roleList = roleDao.findAll();
return roleList;
}
}
④ 创建RoleDao
package com.zd.dao;
import com.zd.domain.Role;
import java.util.List;
public interface RoleDao {
List<Role> findAll();
}
dao —— RoleDao —— RoleDaoImpl(使用JdbcTemplate完成查询操作)
package com.zd.dao.impl;
import com.zd.dao.RoleDao;
import com.zd.domain.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class RoleDaoImpl implements RoleDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Role> findAll() {
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
return roleList;
}
}
配置文件
log4j.properties
### 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.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
spring-mvc.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--① mvc注解驱动--> <mvc:annotation-driven/> <!--② 配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--③ 静态资源权限开放--> <mvc:default-servlet-handler/> <!--④ 组件扫描 扫描Controller --> <context:component-scan base-package="com.zd.controller"/> </beans>
applicationContext.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--① 加载jdbc.properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--② 配置数据源对象--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--③ 配置JdbcTemplate对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置RoleService--> <bean id="roleService" class="com.zd.service.impl.RoleServiceImpl"> <property name="roleDao" ref="roleDao"/> </bean> <!-- 配置RoleDao--> <bean id="roleDao" class="com.zd.dao.impl.RoleDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>
role_list.jsp
<tbody> <c:forEach items="${roleList}" var="role"> <tr> <td><input name="ids" type="checkbox"></td> <td>${role.id}</td> <td>${role.roleName}</td> <td>${role.roleDesc}</td> <td class="text-center"> <a href="#" class="btn bg-olive btn-xs">删除</a> </td> </tr> </c:forEach> </tbody>
错误记录
错误原因:代码写错
//源代码
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>());
java.lang.IllegalStateException: Mapped class was not specified
//修改后
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
角色添加
@RequestMapping("/save")
public String save(Role role){
roleService.save(role);
return"redirect:/role/list";
}
④ 编写RoleService的save()方法
void save(Role role);
RoleServiceImpl的save()方法
@Override
public void save(Role role) {
roleDao.save(role);
}
void save(Role role);
⑥ 使用JdbcTemplate保存Role数据到sys_role(RoleDaoImpl中的save方法)
@Override
public void save(Role role) {
jdbcTemplate.update("insert into sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
}
⑦ 跳转回角色列表页面
<form action="${pageContext.request.contextPath}/role/save" method="post"> <!-- 正文区域 --> <section class="content"> <!--产品信息--> <div class="panel panel-default"> <div class="panel-heading">角色信息</div> <div class="row data-type"> <div class="col-md-2 title">角色名称</div> <div class="col-md-4 data"> <input type="text" class="form-control" name="roleName" placeholder="角色名称" value=""> </div> <div class="col-md-2 title">角色描述</div> <div class="col-md-4 data"> <input type="text" class="form-control" name="roleDesc" placeholder="角色描述" value=""> </div> </div> </div> <!--订单信息/--> <!--工具栏--> <div class="box-tools text-center"> <button type="submit" class="btn bg-maroon">保存</button> <button type="button" class="btn bg-default" οnclick="history.back(-1);">返回</button> </div> <!--工具栏/--> </section> <!-- 正文区域 /--> </form>
<!--配置全局过滤的filter--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
② 创建RoleController
package com.zd.controller;
import com.zd.domain.Role;
import com.zd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@RequestMapping("/role")
@Controller
public class RoleController {
@Autowired
private RoleService roleService;
@RequestMapping("/save")
public String save(Role role){
roleService.save(role);
return "redirect:/role/list";
}
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
//设置模型
modelAndView.addObject("roleList",roleList);
//设置视图
modelAndView.setViewName("role-list");
System.out.println(roleList);
return modelAndView;
}
}
service —— RoleService
package com.zd.service;
import com.zd.domain.Role;
import java.util.List;
public interface RoleService {
public List<Role> list() ;
void save(Role role);
}
service —— impl —— RoleServiceImpl
package com.zd.service.impl;
import com.zd.dao.RoleDao;
import com.zd.domain.Role;
import com.zd.service.RoleService;
import java.util.List;
public class RoleServiceImpl implements RoleService {
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public List<Role> list() {
List<Role> roleList = roleDao.findAll();
return roleList;
}
@Override
public void save(Role role) {
}
}
dao —— RoleDao
package com.zd.dao;
import com.zd.domain.Role;
import java.util.List;
public interface RoleDao {
List<Role> findAll();
}
dao —— RoleDao —— RoleDaoImpl
package com.zd.dao.impl;
import com.zd.dao.RoleDao;
import com.zd.domain.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class RoleDaoImpl implements RoleDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Role> findAll() {
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
return roleList;
}
}
配置文件
log4j.properties
### 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.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
spring-mvc.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--① mvc注解驱动--> <mvc:annotation-driven/> <!--② 配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--③ 静态资源权限开放--> <mvc:default-servlet-handler/> <!--④ 组件扫描 扫描Controller --> <context:component-scan base-package="com.zd.controller"/> </beans>
applicationContext.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--① 加载jdbc.properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--② 配置数据源对象--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--③ 配置JdbcTemplate对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置RoleService--> <bean id="roleService" class="com.zd.service.impl.RoleServiceImpl"> <property name="roleDao" ref="roleDao"/> </bean> <!-- 配置RoleDao--> <bean id="roleDao" class="com.zd.dao.impl.RoleDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>
role_list.jsp
<tbody> <c:forEach items="${roleList}" var="role"> <tr> <td><input name="ids" type="checkbox"></td> <td>${role.id}</td> <td>${role.roleName}</td> <td>${role.roleDesc}</td> <td class="text-center"> <a href="#" class="btn bg-olive btn-xs">删除</a> </td> </tr> </c:forEach> </tbody>
错误记录
错误原因:代码写错
//源代码
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>());
java.lang.IllegalStateException: Mapped class was not specified
//修改后
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
角色添加的步骤
@RequestMapping("/save")
public String save(Role role){
roleService.save(role);
return"redirect:/role/list";
}
④ 编写RoleService的save()方法
void save(Role role);
RoleServiceImpl的save()方法
@Override
public void save(Role role) {
roleDao.save(role);
}
void save(Role role);
⑥ 使用JdbcTemplate保存Role数据到sys_role(RoleDaoImpl中的save方法)
@Override
public void save(Role role) {
jdbcTemplate.update("insert into sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
}
⑦ 跳转回角色列表页面
<form action="${pageContext.request.contextPath}/role/save" method="post"> <!-- 正文区域 --> <section class="content"> <!--产品信息--> <div class="panel panel-default"> <div class="panel-heading">角色信息</div> <div class="row data-type"> <div class="col-md-2 title">角色名称</div> <div class="col-md-4 data"> <input type="text" class="form-control" name="roleName" placeholder="角色名称" value=""> </div> <div class="col-md-2 title">角色描述</div> <div class="col-md-4 data"> <input type="text" class="form-control" name="roleDesc" placeholder="角色描述" value=""> </div> </div> </div> <!--订单信息/--> <!--工具栏--> <div class="box-tools text-center"> <button type="submit" class="btn bg-maroon">保存</button> <button type="button" class="btn bg-default" οnclick="history.back(-1);">返回</button> </div> <!--工具栏/--> </section> <!-- 正文区域 /--> </form>
<!--配置全局过滤的filter--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
用户列表的展示
<li><a href="${pageContext.request.contextPath}/user/list"> <i class="fa fa-circle-o"></i> 用户管理</a></li>
② 创建UserController
package com.zd.controller;
import com.zd.domain.User;
import com.zd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<User> userList = userService.list();
//设置模型
modelAndView.addObject("userList",userList);
//设置视图
modelAndView.setViewName("user-list");
return modelAndView;
}
}
package com.zd.service;
import com.zd.domain.User;
import java.util.List;
public interface UserService {
public List<User> list();
}
UserServiceImpl 的 list()方法 将查询数据存储到Model中
package com.zd.service.impl;
import com.zd.dao.RoleDao;
import com.zd.dao.UserDao;
import com.zd.domain.Role;
import com.zd.domain.User;
import com.zd.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
public List<User> list() {
List<User> userList = userDao.findAll();
//封装userList中的每一个User的roles数据
for (User user : userList) {
//获得user的id
Long id = user.getId();
//将id作为参数 查询当前userId对应的Role集合数据
List<Role> roles = roleDao.findRoleByUserId(id);
user.setRoles(roles);
}
return userList;
}
}
④ 创建UserDao
package com.zd.dao;
import com.zd.domain.User;
import java.util.List;
public interface UserDao {
List<User> findAll();
}
UserDaoImpl 使用JdbcTemplate完成查询操作
package com.zd.dao.impl;
import com.zd.dao.UserDao;
import com.zd.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<User> findAll() {
List<User> userList = jdbcTemplate.query("select * from sys_user ", new BeanPropertyRowMapper<User>(User.class));
return userList;
}
}
RoleDao 增添 findRoleByUserId() 方法
List<Role> findRoleByUserId(Long id);
RoleDaoImpl
@Override
public List<Role> findRoleByUserId(Long id) {
List<Role> roles = jdbcTemplate.query("select * from sys_user_role ur,sys_role r where ur.roleId=r.id and ur.userId=?", new BeanPropertyRowMapper<Role>(Role.class), id);
return roles;
}
⑤ 转发到user-list.jsp页面进行展示
<tbody> <c:forEach items="${userList}" var="user"> <tr> <td><input name="ids" type="checkbox"></td> <td>${user.id}</td> <td>${user.username}</td> <td>${user.email}</td> <td>${user.phoneNum}</td> <td class="text-center"> <c:forEach items="${user.roles}" var="role"> ${role.roleName} </c:forEach> </td> <td class="text-center"> <a href="javascript:void(0);" οnclick="delUser('${user.id}')" class="btn bg-olive btn-xs">删除</a> </td> </tr> </c:forEach> </tbody>
配置文件:applicationContext.xml
<!-- 配置UserService--> <bean id="userService" class="com.zd.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> <property name="RoleDao" ref="roleDao"/> </bean> <!-- 配置UserDao--> <bean id="userDao" class="com.zd.dao.impl.UserDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean>
用户添加
<button type="button" class="btn btn-default" title="新建" οnclick="location.href='${pageContext.request.contextPath}/user/saveUI'"> <i class="fa fa-file-o"></i> 新建 </button>
@RequestMapping("/save")
//Long[] roleIds 存储用户角色
public String save(User user,Long[] roleIds){
userService.save(user, roleIds);
return "redirect:/user/list";//跳转回角色列表页面
}
@RequestMapping("/saveUI")
public ModelAndView saveUI(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
//设置模型
modelAndView.addObject("roleList",roleList);
//设置视图
modelAndView.setViewName("user-add");
return modelAndView;
}
④ 编写UserService的save()方法
void save(User user, Long[] roleIds);
UserServiceImpl
@Override
public void save(User user, Long[] roleIds) {
//第一步 向user表中存储数据
Long userId = userDao.save(user);
//第二步 向role表中存储多条数据
userDao.saveUserRoleRel(userId,roleIds);
}
⑤ 编写UserDao的save()方法
Long save(User user);
void saveUserRoleRel(Long id, Long[] roleIds);
UserDaoImpl 使用JdbcTemplate保存Role数据到sys_role
@Override
public Long save(final User user) {
//创建PreparedStatementCreator
PreparedStatementCreator creator =new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
//使用原始jdbc完成有个preparedStatement的组件
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);
preparedStatement.setString(2,user.getUsername());
preparedStatement.setString(3,user.getEmail());
preparedStatement.setString(4,user.getPassword());
preparedStatement.setString(5,user.getPhoneNum());
return preparedStatement;
}
};
//创建keyHolder
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(creator,keyHolder);
//获得生成的主键
long userId = keyHolder.getKey().longValue();
//jdbcTemplate.update("insert into sys_user values(?,?,?,?)",null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
return userId;//返回当前保存用户的id,该id是数据库自动生成的
}
@Override
public void saveUserRoleRel(Long userId, Long[] roleIds) {
for(Long roleId:roleIds)
jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
}
<div class="col-md-2 title">用户角色</div> <div class="col-md-10 data"> <c:forEach items="${roleList}" var="role"> <input class="" type="checkbox" name="roleIds" value="${role.id}">${role.roleName} </c:forEach> </div>
删除用户
<td class="text-center">
<a href="javascript:void(0);" onclick="delUser('${user.id}')" class="btn bg-olive btn-xs">删除</a>
</td>
<!-- 写入head中 --> <script> function delUser(userId){ if(confirm("您确定要删除嘛")){ location.href="${pageContext.request.contextPath}/user/del/"+userId; } } </script>
<script> function delUser(userId){ if(confirm("您确定要删除嘛")){ location.href="${pageContext.request.contextPath}/user/del"+userId; <!-- del后面少了一个“ / ” 导致页面不存在报404错误 --> } } </script>
@RequestMapping("/del/{userId}")
public String del(@PathVariable("userId") Long userId){
userService.del(userId);
return "redirect:/user/list";//跳回当前用户列表页面
}
void del(Long userId);
UserServiceImpl
@Override
public void del(Long userId) {
//1、删除role关系表中的数据
userDao.delUerRoleRel(userId);
//2、删除user中的数据
userDao.del(userId);
}
④ UserDao
void delUerRoleRel(Long userId);
void del(Long userId);
UserDaoImpl
@Override
public void delUerRoleRel(Long userId) {
jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
}
@Override
public void del(Long userId) {
jdbcTemplate.update("delete from sys_user where id=?",userId);
}
⑤ UserDao
void delUerRoleRel(Long userId);
void del(Long userId);