SpringMVC练习

SpringMVC练习


1.角色列表role-list
  1. 当用户点击角色管理时,发送req请求到服务端
  2. 在服务端找web层中的某个方法,负责把请求传递到业务层、dao层、通过jdbcTemplate模板对数据库进行查询,
  3. 将查询到的数据,原路进行依次返回,
  4. 最终返回到达web层时,将数据存储到modelAndView中
  5. 最后转发到页面role-list.jsp页面进行展示
@RequestMapping("/role")
@Controller
public class RoleController {
    //roleService依赖注入
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        //1.调用service层方法进行数据查询
        List<Role> roleList = roleService.list();
        //2.将查询数据结果与jsp视图封装到modelAndView中
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }
}
public class RoleServiceImpl implements RoleService {
    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }
    
    public List<Role> list() {
        List<Role> roleList = roleDao.findAll();
        return roleList;
    }
}
public class RoleDaoImpl implements RoleDao {
    //jdbcTemplate依赖注入
    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;
    }
}
<?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">
    <!--1.mvc注解驱动-->
    <mvc:annotation-driven/>
    <!--2.配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--3.静态资源访问权限开放-->
    <mvc:default-servlet-handler/>
    <!--4.注解扫描 扫描controller-->
    <context:component-scan base-package="com.itcast.controller"/>

</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: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">
    <!--1.加载外部的jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--2.配置数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--3.配置jdbc模板对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置RoleService-->
    <bean id="roleService" class="com.itcast.service.impl.RoleServiceImpl">
        <property name="roleDao" ref="roleDao"/>
    </bean>
    <!--配置RoleDao-->
    <bean id="roleDao" class="com.itcast.dao.impl.RoleDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--1.解决乱码问题的过滤器-->
    <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>
    <!--2.配置spring-->
    <!--全局化参数-->
    <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>
    <!--3.配置springmvc-->
    <!--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>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

在这里插入图片描述

2.角色添加role-add
  1. 点击列表页面新建按钮跳转到角色添加页面
  2. 输入角色信息,点击保存按钮后表达数据提交到服务器
  3. 在服务端找web层中的某个方法,负责把数据传递到业务层、dao层、通过jdbcTemplate模板对数据库进行写入,
  4. 跳转回角色列表页面
@RequestMapping("/role")
@Controller
public class RoleController {
    //roleService依赖注入
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        //1.调用service层方法进行数据查询
        List<Role> roleList = roleService.list();
        //2.将查询数据结果与jsp视图封装到modelAndView中
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(Role role) {
        roleService.save(role);
        return "redirect:/role/list";
    }
}
public class RoleServiceImpl implements RoleService {
    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<Role> list() {
        List<Role> roleList = roleDao.findAll();
        return roleList;
    }

    public void save(Role role) {
        roleDao.save(role);
    }
}
public class RoleDaoImpl implements RoleDao {
    //jdbcTemplate依赖注入
    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;
    }

    public void save(Role role) {
        jdbcTemplate.update("insert into sys_role values (?, ?, ?)", null, role.getRoleName(), role.getRoleDesc());
    }
}

在这里插入图片描述

3.角色删除
<!--数据列表-->
<table id="dataList" class="table table-bordered table-striped table-hover dataTable">
	<thead>
		<tr>
			<th class="" style="padding-right: 0px"><input id="selall" type="checkbox" class="icheckbox_square-blue">
			</th>
			<th class="sorting_asc">ID</th>
			<th class="sorting_desc">角色名称</th>
			<th class="sorting">角色描述</th>
			<th class="sorting">操作</th>
		</tr>
	</thead>
	<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="#" onclick="delRole('${role.id}')" class="btn bg-olive btn-xs">删除</a>
				</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<!--数据列表/-->
<script>
	function delRole(roleId) {
		if (confirm("您确认要删除吗")) {
			//发送请求进行删除处理
			location.href = "${pageContext.request.contextPath}/role/del/" + roleId;
		}
	}
</script>
package com.itcast.controller;

import com.itcast.domain.Role;
import com.itcast.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RequestMapping("/role")
@Controller
public class RoleController {
    //roleService依赖注入
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        //1.调用service层方法进行数据查询
        List<Role> roleList = roleService.list();
        //2.将查询数据结果与jsp视图封装到modelAndView中
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(Role role) {
        roleService.save(role);
        return "redirect:/role/list";
    }

    @RequestMapping("/del/{roleId}")
    public String del(@PathVariable("roleId") long roleId) {
        roleService.del(roleId);
        return "redirect:/role/list";
    }
}
package com.itcast.service.impl;

import com.itcast.dao.RoleDao;
import com.itcast.domain.Role;
import com.itcast.service.RoleService;

import java.util.List;

public class RoleServiceImpl implements RoleService {
    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<Role> list() {
        List<Role> roleList = roleDao.findAll();
        return roleList;
    }

    public void save(Role role) {
        roleDao.save(role);
    }

    public void del(long roleId) {
        //1.删除sys_user_role关系表
        roleDao.delUserRole(roleId);
        //2.删除sys_role表
        roleDao.del(roleId);
    }
}
package com.itcast.dao.impl;

import com.itcast.dao.RoleDao;
import com.itcast.domain.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class RoleDaoImpl implements RoleDao {
    //jdbcTemplate依赖注入
    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;
    }

    public void save(Role role) {
        jdbcTemplate.update("insert into sys_role values (?, ?, ?)", null, role.getRoleName(), role.getRoleDesc());
    }

    public List<Role> findRoleByUserId(Long id) {
        List<Role> roleList = 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 roleList;
    }

    public void delUserRole(long roleId) {
        jdbcTemplate.update("delete from sys_user_role where roleId = ?", roleId);
    }

    public void del(long roleId) {
        jdbcTemplate.update("delete from sys_role where id = ?", roleId);
    }
}

在这里插入图片描述

4.用户列表user-list
<!--数据列表-->
<table id="dataList" class="table table-bordered table-striped table-hover dataTable">
	<thead>
		<tr>
			<th class="" style="padding-right: 0px">
				<input id="selall" type="checkbox" class="icheckbox_square-blue">
			</th>
			<th class="sorting_asc">ID</th>
			<th class="sorting_desc">用户名</th>
			<th class="sorting_asc sorting_asc_disabled">邮箱</th>
			<th class="sorting_desc sorting_desc_disabled">联系电话</th>
			<th class="sorting">具有角色</th>
			<th class="sorting">操作</th>
		</tr>
	</thead>
	<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.roleList}" var="role">
						&nbsp;&nbsp;${role.roleName}
					</c:forEach>
				</td>
				<td class="text-center">
					<a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
				</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<!--数据列表/-->
@RequestMapping("/role")
@Controller
public class RoleController {
    //roleService依赖注入
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        //1.调用service层方法进行数据查询
        List<Role> roleList = roleService.list();
        //2.将查询数据结果与jsp视图封装到modelAndView中
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }
}
public class UserServiceImpl implements UserService {
    //userDao依赖注入
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {
        //1.从user表中查询到所有用户信息
        List<User> userList = userDao.findAll();
        //2.从userList中查询每一个User对应的相关roleList数据
        for (User user : userList) {
            //1.获得user的id
            Long id = user.getId();
            //2.将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roleList = roleDao.findRoleByUserId(id);
            user.setRoleList(roleList);
        }
        //3.返回最后封装完整的userList数据集
        return userList;
    }
}
public class UserDaoImpl implements UserDao {
    //注入jdbc模板
    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;
    }
}
public class RoleDaoImpl implements RoleDao {
    //jdbcTemplate依赖注入
    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;
    }

    public void save(Role role) {
        jdbcTemplate.update("insert into sys_role values (?, ?, ?)", null, role.getRoleName(), role.getRoleDesc());
    }

    public List<Role> findRoleByUserId(Long id) {
        List<Role> roleList = 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 roleList;
    }
}

在这里插入图片描述

5.用户添加user-add
<!-- 内容头部 /-->
<form action="${pageContext.request.contextPath}/user/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="username" placeholder="用户名称" value="">
				</div>
				<div class="col-md-2 title">密码</div>
				<div class="col-md-4 data">
					<input type="password" class="form-control" name="password" placeholder="密码" value="">
				</div>
				<div class="col-md-2 title">邮箱</div>
				<div class="col-md-4 data">
					<input type="text" class="form-control" name="email" placeholder="邮箱" value="">
				</div>
				<div class="col-md-2 title">联系电话</div>
				<div class="col-md-4 data">
					<input type="text" class="form-control" name="phoneNum" placeholder="联系电话" value="">
				</div>
				<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>

			</div>
		</div>
		<!--订单信息/-->
		<!--工具栏-->
		<div class="box-tools text-center">
			<button type="submit" class="btn bg-maroon">保存</button>
			<button type="button" class="btn bg-default" onclick="history.back(-1);">返回</button>
		</div>
		<!--工具栏/-->
	</section>
	<!-- 正文区域 /-->
</form>
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        List<User> userList = userService.list();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI() {
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user, Long[] roleIds) {
        userService.save(user, roleIds);
        return "redirect:/user/list";
    }
}
public class UserServiceImpl implements UserService {
    //userDao依赖注入
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {
        //1.从user表中查询到所有用户信息
        List<User> userList = userDao.findAll();
        //2.从userList中查询每一个User对应的相关roleList数据
        for (User user : userList) {
            //1.获得user的id
            Long id = user.getId();
            //2.将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roleList = roleDao.findRoleByUserId(id);
            user.setRoleList(roleList);
        }
        //3.返回最后封装完整的userList数据集
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //1.向sys_user表中存储数据
        Long userId = userDao.save(user);
        //2.向sys_user_role关系表中存储多条数据
        userDao.saveUserRoles(userId, roleIds);
    }
}
public class UserDaoImpl implements UserDao {
    //注入jdbc模板
    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;
    }

    public Long save(final User user) {
        //1.创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            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;
            }
        };
        //2.创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        //3.将数据保存到user表中
        jdbcTemplate.update(creator, keyHolder);
        //4.获得user表中自动生成的主键UserId
        long userId = keyHolder.getKey().longValue();
        return userId;//(autoincrement)
    }

    public void saveUserRoles(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?, ?)", userId, roleId);
        }
    }
}

在这里插入图片描述

6.用户删除
<!--数据列表-->
<table id="dataList" class="table table-bordered table-striped table-hover dataTable">
	<thead>
		<tr>
			<th class="" style="padding-right: 0px">
				<input id="selall" type="checkbox" class="icheckbox_square-blue">
			</th>
			<th class="sorting_asc">ID</th>
			<th class="sorting_desc">用户名</th>
			<th class="sorting_asc sorting_asc_disabled">邮箱</th>
			<th class="sorting_desc sorting_desc_disabled">联系电话</th>
			<th class="sorting">具有角色</th>
			<th class="sorting">操作</th>
		</tr>
	</thead>
	<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.roleList}" var="role">
						&nbsp;&nbsp;${role.roleName}
					</c:forEach>
				</td>
				<td class="text-center">
					<a href="javascript:void(0);" onclick="delUser('${user.id}')" class="btn bg-olive btn-xs">删除</a>
				</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<!--数据列表/-->
<script>
	function delUser(userId) {
		if (confirm("您确认要删除吗")) {
			//发送请求进行删除处理
			location.href = "${pageContext.request.contextPath}/user/del/" + userId;
		}
	}
</script>
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list() {
        List<User> userList = userService.list();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI() {
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user, Long[] roleIds) {
        userService.save(user, roleIds);
        return "redirect:/user/list";
    }

    @RequestMapping("/del/{userId}")
    public String del(@PathVariable("userId") long userId) {
        userService.del(userId);
        return "redirect:/user/list";
    }
}
public class UserServiceImpl implements UserService {
    //userDao依赖注入
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    //roleDao依赖注入
    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {
        //1.从user表中查询到所有用户信息
        List<User> userList = userDao.findAll();
        //2.从userList中查询每一个User对应的相关roleList数据
        for (User user : userList) {
            //1.获得user的id
            Long id = user.getId();
            //2.将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roleList = roleDao.findRoleByUserId(id);
            user.setRoleList(roleList);
        }
        //3.返回最后封装完整的userList数据集
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //1.向sys_user表中存储数据
        Long userId = userDao.save(user);
        //2.向sys_user_role关系表中存储多条数据
        userDao.saveUserRoles(userId, roleIds);
    }

    public void del(long userId) {
        //1.删除sys_user_role关系表
        userDao.delUserRole(userId);
        //2.删除sys_user表
        userDao.del(userId);
    }
}
public class UserDaoImpl implements UserDao {
    //注入jdbc模板
    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;
    }

    public Long save(final User user) {
        //1.创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            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;
            }
        };
        //2.创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        //3.将数据保存到user表中
        jdbcTemplate.update(creator, keyHolder);
        //4.获得user表中自动生成的主键UserId
        long userId = keyHolder.getKey().longValue();
        return userId;//(autoincrement)
    }

    public void saveUserRoles(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?, ?)", userId, roleId);
        }
    }

    public void delUserRole(long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ?", userId);
    }

    public void del(long userId) {
        jdbcTemplate.update("delete from sys_user where id = ?", userId);
    }
}

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值