一、数据库及实体类创建
数据库:
实体类: Role
public class Role {
private Long id;
private String roleName;
private String roleDesc;
get/set/toString;
}
User
public class User {
private Long id;
private String username;
private String email;
private String password;
private String phoneNum;
private List<Role> roles;
get/set/toString;
}
二、配置文件
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
2.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http:
http:
http:
http:
">
<!--1、数据源-->
<!-- 外部加载jdbc文件 -->
<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>
<!-- 2、配置jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
3.sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--通过properties标签加载外部properties文件-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.domain.User" alias="user"></typeAlias>
<typeAlias type="com.domain.Role" alias="role"></typeAlias>
</typeAliases>
<!--加载映射关系-->
<mappers>
<!--指定接口所在的包-->
<package name="com.dao"></package>
</mappers>
</configuration>
4.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:
http:
http:
">
<!--1、mvc注解驱动-->
<mvc:annotation-driven/>
<!--2、配置内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp -->
<property name="prefix" value="/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--3、静态资源权限开放-->
<!-- <mvc:resources mapping="/js/**" location="/js/"/>-->
<!-- Tomcat找静态资源 -->
<mvc:default-servlet-handler/>
<!--4、组件扫描:扫描Controller-->
<context:component-scan base-package="com.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
5.web.xml
<?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">
<!--全局初始化参数-->
<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>
<!-- 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>
<!--解决乱码的过滤器-->
<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>
三、功能实现
1.角色增删查
控制层Controller:
@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";
}
}
业务逻辑层Service service接口:
public interface RoleService {
public List<Role> list();
void save(Role role);
void del(Long roleId);
}
接口实现类:
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleDao roleDao;
@Override
public List<Role> list() {
List<Role> roleList = roleDao.findAll();
return roleList;
}
@Override
public void save(Role role) {
roleDao.save(role);
}
@Override
public void del(Long roleId) {
roleDao.delRoleRel(roleId);
roleDao.del(roleId);
}
}
持久层Dao
public interface RoleDao {
@Select("select * from sys_role")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "roleName", property = "roleName"),
@Result(column = "roleDesc", property = "roleDesc"),
})
List<Role> findAll();
@Insert("insert into sys_role values(#{id},#{roleName},#{roleDesc})")
void save(Role role);
@Select("select * from sys_user_role ur,sys_role r where ur.roleId=r.id and ur.userId=#{id}")
List<Role> findRoleByUserId(@Param("id") Long id);
@Delete("delete from sys_user_role where roleId=#{roleId}")
void delRoleRel(@Param("roleId") Long roleId);
@Delete("delete from sys_role where id=#{roleId}")
void del(@Param("roleId") Long roleId);
}
效果展示:
2.用户增删查
控制层Controller:
@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView();
List<User> userList = userService.list();
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) throws Exception {
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";
}
}
业务逻辑层Service service接口:
public interface UserService {
public List<User> list();
void save(User user, Long[] roleIds);
void del(Long userId);
}
接口实现类:
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Override
public List<User> list() {
List<User> userList = userDao.findAll();
for (User user : userList) {
Long id = user.getId();
List<Role> roles = roleDao.findRoleByUserId(id);
user.setRoles(roles);
}
return userList;
}
@Override
public void save(User user, Long[] roleIds) {
userDao.save(user);
for (Long roleId : roleIds) {
userDao.saveUserRoleRel(user.getId(), roleId);
}
}
@Override
public void del(Long userId) {
userDao.delUserRoleRel(userId);
userDao.del(userId);
}
}
持久层Dao
public interface UserDao {
@Select("SELECT * FROM sys_user")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "email", property = "email"),
@Result(column = "phoneNum", property = "phoneNum"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.dao.RoleDao")
)
})
List<User> findAll();
@Insert("insert into sys_user values(#{id},#{username},#{email},#{password},#{phoneNum})")
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
Long save(User user);
@Insert("insert into sys_user_role values(#{userId},#{roleIds})")
void saveUserRoleRel(@Param("userId") Long userId, @Param("roleId") Long roleId);
@Delete("delete from sys_user_role where userId=#{userId}")
void delUserRoleRel(@Param("userId") Long userId);
@Delete("delete from sys_user where id=#{userId}")
void del(@Param("userId") Long userId);
效果展示:
|