SpringMVC练习
1.角色列表role-list
- 当用户点击角色管理时,发送req请求到服务端
- 在服务端找web层中的某个方法,负责把请求传递到业务层、dao层、通过jdbcTemplate模板对数据库进行查询,
- 将查询到的数据,原路进行依次返回,
- 最终返回到达web层时,将数据存储到modelAndView中
- 最后转发到页面role-list.jsp页面进行展示
@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");
return modelAndView;
}
}
public class RoleServiceImpl implements RoleService {
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 {
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">
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:default-servlet-handler/>
<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">
<context:property-placeholder location="classpath:jdbc.properties"/>
<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>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="roleService" class="com.itcast.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<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">
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
![在这里插入图片描述](https://img-blog.csdnimg.cn/4b3fd3f2bd5e4cbd8f33a042ab8f979d.png#pic_center)
2.角色添加role-add
- 点击列表页面新建按钮跳转到角色添加页面
- 输入角色信息,点击保存按钮后表达数据提交到服务器
- 在服务端找web层中的某个方法,负责把数据传递到业务层、dao层、通过jdbcTemplate模板对数据库进行写入,
- 跳转回角色列表页面
@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");
return modelAndView;
}
@RequestMapping("/save")
public String save(Role role) {
roleService.save(role);
return "redirect:/role/list";
}
}
public class RoleServiceImpl implements RoleService {
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 {
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());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/36e1f46229444ec7bc116b40133e7d58.png#pic_center)
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 {
@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");
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 {
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) {
roleDao.delUserRole(roleId);
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 {
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);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/adbb33298fd749cab2026ead0a264b2f.png#pic_center)
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">
${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 {
@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");
return modelAndView;
}
}
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();
for (User user : userList) {
Long id = user.getId();
List<Role> roleList = roleDao.findRoleByUserId(id);
user.setRoleList(roleList);
}
return userList;
}
}
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;
}
}
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;
}
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;
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/b7ab09771cf94d5e861b6fd80b407f3f.png#pic_center)
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 {
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();
for (User user : userList) {
Long id = user.getId();
List<Role> roleList = roleDao.findRoleByUserId(id);
user.setRoleList(roleList);
}
return userList;
}
public void save(User user, Long[] roleIds) {
Long userId = userDao.save(user);
userDao.saveUserRoles(userId, roleIds);
}
}
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;
}
public Long save(final User user) {
PreparedStatementCreator creator = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
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;
}
};
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(creator, keyHolder);
long userId = keyHolder.getKey().longValue();
return userId;
}
public void saveUserRoles(Long userId, Long[] roleIds) {
for (Long roleId : roleIds) {
jdbcTemplate.update("insert into sys_user_role values(?, ?)", userId, roleId);
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/87cee681877b4da1be32c781adf89ed1.png#pic_center)
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">
${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 {
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();
for (User user : userList) {
Long id = user.getId();
List<Role> roleList = roleDao.findRoleByUserId(id);
user.setRoleList(roleList);
}
return userList;
}
public void save(User user, Long[] roleIds) {
Long userId = userDao.save(user);
userDao.saveUserRoles(userId, roleIds);
}
public void del(long userId) {
userDao.delUserRole(userId);
userDao.del(userId);
}
}
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;
}
public Long save(final User user) {
PreparedStatementCreator creator = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
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;
}
};
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(creator, keyHolder);
long userId = keyHolder.getKey().longValue();
return userId;
}
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);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/4d2c0b3dc12c4df882814e396c368df5.png#pic_center)