文章目录
一、Spring练习环境搭建
1.1 Spring环境搭建步骤
①创建工程( Project& Module)
②导入静态页面见资料jsp页面)
③导入需要坐标
④创建包结构( controller、 service、dao、 domain、utls
⑤导入数据库脚本(见资料 test.sa)
⑥创建POJO类(见资料 User java和Role java)
⑦创建配置文件( applicationContext xml、 spring- mvc.xml、web.xml、 jdbc properties、log4g-properties)
导入需要的坐标
<?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>itheima_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>
<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>
<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>
<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>
配置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>
</web-app>
配置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"
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">
<!--1、mvc注解驱动-->
<mvc:annotation-driven/>
<!--2、配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--静态资源的访问权限的开放-->
<mvc:default-servlet-handler/>
</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">
<!--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.Drivetr}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--3、配置JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
1.2 用户和角色的关系
sys_role表
sys_user_role表
sys_user表
二、角色列表的展示和添加操作
2.1 角色列表的展示效果
按图索骥 请求服务器端(找web层中的Controller中的某个方法,这个方法负责把请求传递到业务层)->业务层->dao层->通过jdbcTemplate进行查询(查到的数据依次返回)->最终到达web层,把数据存到modelAndView中转发到该页面进行展示。
项目目录结构:
RoleDaoImpl
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;
}
}
RoleServiceImpl
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;
}
}
RoleController
@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;
}
}
依赖注入application.xml
<!--3、配置JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置RoleService-->
<bean id="roleService" class="com.itheima.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<!--配置roleDao-->
<bean id="roleDao" class="com.itheima.dao.impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
spring-mvc.xml
<!--4、组件扫描 扫描Controller-->
<context:component-scan base-package="com.itheima.controller"/>
2.2 角色列表的展示步骤分析
①点击角色管理菜单发送请求到服务器端(修改角色管理菜单的ur地址)
②创建 Rolecontroller和 showList()方法
③创建 Roleservice和 showList()方法
④创建 Roledao和findAll()方法
⑤使用 JdbcTemplate完成查询操作
⑥将查询数据存储到Mode中
⑦转发到role-list jsp页面进行展示
2.3 角色添加的效果
2.4 角色添加的步骤分析
①点击列表页面新建按钮跳转到角色添加页面
②输入角色信息,点击保存按钮,表单数据提交服务器
③编写 RoleController的save()方法
④编写 Roleservice的 save方法
⑤编写 Soledad的save()方法
⑥使用 JdbcTemplate保存Role数据到 sys_role
⑦跳转回角色列表页面
访问测试角色管理:
@RequestMapping("/save")
public String save(Role role) {
roleService.save(role);
return "redirect:/role/list";
}
这里出现了乱码问题,为什么呢?因为我们发送的是post请求,服务器并没有帮我们解决乱码问题,所以我们要自己手动设置编码格式。
在```web.xml`中配置解决乱码问题的过滤器
<!--解决POST乱码问题的过滤器-->
<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>
添加
这下乱码问题就解决了!
三、用户列表的展示和添加操作
3.1 用户列表的展示效果
3.2 用户列表的展示步骤分析
①点击用户管理菜单发送请求到服务器端(修改用户管理菜单的ur地址)
②创建 RoleController和 showList()方法
③创建 Roleservice和 showList()方法
④创建 Roledao和findAll()方法
⑤使用 JdbcTemplate完成查询操作
⑥将查询数据存储到Model中
⑦转发到user-list.jsp页面进行展示
User
public class User {
private Long id;
private String username;
private String email;
private String password;
private String phoneNum;
/*用户拥有的角色*/
private List<Role> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", phoneNum='" + phoneNum + '\'' +
'}';
}
}
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setUserdao(UserDao userdao) {
this.userDao = userdao;
}
public List<User> list() {
return userDao.findAll();
}
}
UserDaoImpl
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;
}
}
UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public ModelAndView lsit() {
List<User> userList = userService.list();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userList", userList);
modelAndView.setViewName("user-list");
return modelAndView;
}
}
user-list.jsp
<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">
课程研究员 讲师
</td>
<td class="text-center">
<a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
</td>
</tr>
</c:forEach>
在applicationContext.xml
中配置注入
<!--配置roleDao-->
<bean id="roleDao" class="com.itheima.dao.impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!--配置UserServicee-->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userdao" ref="userDao"/>
</bean>
<!--配置UserDao-->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
但是到这里还是不完善的,因为具有角色还没有展现出来
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.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的rolse数据
for (User user : userList) {
//获得user的id
Long id = user.getId();
//将Id作为参数 查询当前userId对应的Role集合数据
List<Role> roles = roleDao.findRoleById(id);
user.setRoles(roles);
}
return userList;
}
}
<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);" class="btn bg-olive btn-xs">删除</a>
</td>
</tr>
</c:forEach>
RoleDaoImpl
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> findRoleById(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);
System.out.println(roles);
return roles;
}
}
roles
的值:
配置applicationContext.xml
<!--配置UserServicee-->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<!--注入userDao-->
<property name="userdao" ref="userDao"/>
<!--注入RoleDao-->
<property name="roleDao" ref="roleDao"/>
</bean>
3.3 用户添加的效果
3.4 用户添加的步骤分析
①点击列表页面新建按钮跳转到角色添加页面
②输入角色信息,点击保存按钮,表单数据提交服务器
③编写 Role Controller的save0方法
④编写R. preservice的save0方法
⑤编写 RoleDa。的save0方法
⑥使用 Jdbctemplate保存Roe数据到 Isys role
⑦跳转回角色列表页面
1)显示用户角色
@RequestMapping("/saveUI")
public ModelAndView saveUI() {
List<Role> roleList = roleService.list();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("roleList", roleList);
modelAndView.setViewName("user-add");
return modelAndView;
}
user-add.jsp
<c:forEach items="${roleList}" var="role">
<input class="" type="checkbox" name="roleIds" value="${role.id}">${role.roleName}
</c:forEach>
2)
UserServiceImpl
public void save(User user, long[] roleIds) {
//第一步 向user_user表中存储数据
userDao.save(user);
//第二步 向user_user_role关系吧中存储多条数据
userDao.saveUserRoleRel(user.getId(), roleIds);
}
UserDaoImpl
public void save(User user) {
jdbcTemplate.update("insert into sys_user vales(?,?,?,?,?)", null, user.getUsername(), user.getEmail(), user.getPassword(), user.getPhoneNum());
}
public void saveUserRoleRel(long userId, long[] roleIds) {
for (long roleId : roleIds) {
jdbcTemplate.update("insert into sys_user_role vales(?,?)", userId, roleId);
}
}
添加数据
这里报了500的错误,为什么会这样呢?通过排查发现,userId我们并不知道是什么,也就是表单提交中没有userId,我们可以弄个隐藏域提交id,但是这样不太好,那如果知道插入数据库中的数据的Id呢?将这个id作为唯一标识在插入sys_user_role表中不就好了嘛。那接下来就是如何获取这个id了。
UserServiceImpl
public void save(User user, long[] roleIds) {
//第一步 向user_user表中存储数据
Long userId = userDao.save(user);
//第二步 向user_user_role关系吧中存储多条数据 userId不为空
userDao.saveUserRoleRel(userId, roleIds);
}
UserDaoImpl
public Long save(final User user) {
//创建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;
}
};
//创建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是数据库自动生成的
}
public void saveUserRoleRel(long userId, long[] roleIds) {
for (long roleId : roleIds) {
jdbcTemplate.update("insert into sys_user_role values(?,?)", userId, roleId);
}
}
四、删除用户操作
4.1 删除用户的效果
4.2 删除用户的步骤分析
①点击用户列表的删除按钮,发送请求到服务器端
②编写UserController的deleteByld()方法
③编写UserService的deleteByld()方法
④编写UserDao的delete Byld()方法
⑤编写UserDao的deleteRelByUid()方法
⑥跳回当前用户列表页面
<script type="text/javascript">
function delUser(userId) {
if (confirm("您确定要删除吗?")) {
location.href = "${pageContext.request.contextPath}/user/del/" + userId;
}
}
</script>
①点击用户列表的删除按钮,发送请求到服务器端
②编写UserController的deleteByld()方法
@RequestMapping("/del/{userId}")
public String save(@PathVariable("userId") Long userId) {
userService.del(userId);
return "redirect:/user/list";
}
③编写UserService的deleteByld()方法
public void del(Long userId) {
//删除sys_user_role关系表中的数据
userDao.delUserRoleRel(userId);
//删除sys_user表中的数据
userDao.del(userId);
}
④编写UserDao的deleteByld()方法
⑤编写Userdao的deleteRelByUId()方法
public void delUserRoleRel(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);
}
⑥跳回当前用户列表页面
return "redirect:/user/list";