base黑马,视频链接:https://www.bilibili.com/video/BV1WZ4y1P7Bp?t=94.4
此系列文章可以当做视频的配套笔记,也可以当做自学SSM框架的教程。
Spring练习-环境搭建步骤分析
domain、pojo、entity 都是一个意思。
Spring练习-环境搭建实现1
素材:是在第6天资料里面
Spring练习-环境搭建实现2
web.xml配置文件的初始化
<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><!--这里写2 写1 都行-->
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--写 / 意味着所有的请求都找它-->
<!-- 静态资源 得在 spring-mvc.xml配置文件中进行一个开放-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Spring练习-环境搭建实现3
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/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/>
</beans>
Spring练习-环境搭建实现4
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.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--3、配置JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
Spring练习-用户表和角色表的分析
表的关系都是源于业务模型
把业务搞明白,自然这个表就会设计了
到企业开发当中有时候并不是技术难,而是业务难。
中间表中是外键
把主键放到中间表中去维护
中间表,维护 用户表和 角色表 之间 多对多 之间的关系。
Spring练习-角色列表展示分析
首先 是 找入口
真正到开发中先设计 Dao层
再设计 web层
最后设计 业务层
和web阶段的项目是一模一样
Spring练习-角色列表展示-controller层实现
初始页面是这里:
index.jsp 页面中的重定向
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页</title>
</head>
<body>
<%-- 默认访问到index.jsp,这行代码 又 帮你重定向 到 main.jsp这个页面 --%>
<%
response.sendRedirect(request.getContextPath()+"/pages/main.jsp");
%>
</body>
</html>
页面头部的引用代码
页面导航侧栏的引用代码
内容区域:
底部导航:
侧边是 aside.jsp 所以 打开 aside.jsp
在controller层建立一个RoleController类
package com.lyh.controller;
import com.lyh.domain.Role;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@RequestMapping("/role")
public class RoleController {
//service 层找 spring容器 这个时候service暂时是没有的
private RoleService roleService;
//设置一个set方法,目前先用配置文件的方式,后期的时候,再用注解的方式
public void setRoleService(RoleService roleService) {
this.roleService = roleService;
}
//@RequestMapping("/role/list") //这样写是没有问题的
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
//设置模型对象
modelAndView.addObject("roleList",roleList);
//设置视图 给 role-list.jsp页面中跳转
modelAndView.setViewName("role-list");
return modelAndView;
}
}
Spring练习-角色列表展示-service和dao层实现
创建service层
package com.lyh.service;
import com.lyh.domain.Role;
import java.util.List;
public interface RoleService {
public List<Role> list();
}
package com.lyh.service.impl;
import com.lyh.domain.Role;
import com.lyh.service.RoleService;
import java.util.List;
public class RoleServiceImpl implements RoleService {
//内部调用dao层
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public List<Role> list() {
List<Role> roleList = roleDao.findAll();
return roleList;
}
}
创建dao层
package com.lyh.dao;
import com.lyh.domain.Role;
import java.util.List;
public interface RoleDao {
public List<Role> findAll();
}
package com.lyh.dao.impl;
import com.lyh.dao.RoleDao;
import com.lyh.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;
}
@Override
public List<Role> findAll() { //实体的泛型 + 实体的字节码对象
List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
return roleList;
}
}
Spring练习-角色列表展示-配置实现
需要把 web(controller)、service、dao层,都给放到Spring容器当中。
controller层一般用的是注解。
controller层 上新添加的注解。
package com.lyh.controller;
import com.lyh.domain.Role;
import com.lyh.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 //代表 RoleController 用注解方式,可以分开,一部分用注解,一部分用配置文件的方式
public class RoleController {
//service 层找 spring容器要 这个时候service暂时是没有的
@Autowired
private RoleService roleService;
//用注解的方式,roleService 的 set方法 可以去掉了
//@RequestMapping("/role/list") //这样写是没有问题的
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
//设置模型对象
modelAndView.addObject("roleList",roleList);
//设置视图 给 role-list.jsp页面中跳转
modelAndView.setViewName("role-list");
return modelAndView;
}
}
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/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-->
<!--Service 和 Dao层不用扫描,用配置文件去进行配置-->
<context:component-scan base-package="com.lyh.controller"/>
</beans>
在Spring的配置文件 applicationContext.xml 中 配置 Service层 和 Dao层 的bean
<?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、配置JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置RoleService-->
<bean id="roleService" class="com.lyh.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<!-- 配置RoleDao-->
<bean id="roleDao" class="com.lyh.dao.impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>
web(controller)层用的是注解。
service层和dao层用的是配置文件。
Spring练习-角色列表展示-页面展示
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
modelAndView.addObject("roleList",roleList);//现在的数据存到roleList中了
modelAndView.setViewName("role-list");
return modelAndView;
}
需要使用 jstl+el 去取数据,用for循环进行展示
找到页面 role-list.jsp页面
通过下面的代码在role-list.jsp页面的最上方 引入 jstl
<%--引入jstl--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--这里只剩一个 对这一个进行for循环 var="role"代表集合当中的每个元素--%>
<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>
重启TomCat进行测试:
如果出现这个问题,说明约束引用的有问题。
效果:
Spring练习-角色的添加操作
找到 role-add.jsp这个页面
role-add.jsp 文件中的 form表单
<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"> <!--name要和Role对象的属性的名字一致,这样SpringMVC才能帮助自动封装-->
<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"
onclick="history.back(-1);">返回</button>
</div>
<!--工具栏/--> </section>
<!-- 正文区域 /-->
</form>
controller层添加角色的方法。
//添加角色的方法
@RequestMapping("/save")
//因为提交的都是 Role对象的属性 所以 用Role对象来接收
public String save(Role role){
roleService.save(role);
//这里是跳转到 /role/list 中,这样才会有数据
//所以用重定向
return "redirect:/role/list";
}
service相关层代码:RoleService接口
package com.lyh.service;
import com.lyh.domain.Role;
import java.util.List;
public interface RoleService {
public List<Role> list();
void save(Role role);
}
RoleServiceImpl类中添加相关的代码。
@Override
public void save(Role role) {
roleDao.save(role);
}
RoleDao接口中的相关代码
package com.lyh.dao;
import com.lyh.domain.Role;
import java.util.List;
public interface RoleDao {
public List<Role> findAll();
void save(Role role);
}
RoleDaoImpl类中的添加相关的代码
@Override
public void save(Role role) { //三个占位符,主键是自增的,就不用管了,写成null
jdbcTemplate.update("insert into sys_role values(?,?,?)",null, role.getRoleName(),role.getRoleDesc());
}
重启一下
效果:
后台数据乱码!
原因在于当前表单的提交方式是post,post本身就有乱码问题。
得在web.xml中配置一个CharacterEncodingFilter,帮助解决乱码问题。
web.xml中 解决乱码的过滤器
<!-- 解决乱码的过滤器-->
<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>
测试:
这里 需要将 jdbc.properties 中的 jdbc.url修改为:
jdbc.url=jdbc:mysql://localhost:3306/test**?useUnicode=true&characterEncoding=UTF-8**
乱码的问题将会解决。
Spring练习-用户列表展示1
实际上用户的列表展示 和 角色的差不多,基本上是一样的。
但是难的地方是在这里
表示当前这个用户具备那些角色。
用户表和角色表之间的关系是多对多的关系。
现在这个用户用到了角色的信息了。
在进行实体描述的时候就得描述User实体 与 Role实体的关系。
一个用户可以具有多个角色。
在User类中添加新的属性:
//当前用户具备那些角色
//实体与实体 之间 关系的描述 通过 对象引用
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
现在 用户 在查询的时候,就不能 单表查询了。
因为不能只查询 User表还得查询Role表
但是可以分布查询,先查询用户表,再查询角色表。
最终查询的关系是,多个User
这些User都放到一个集合当中
而每一个User内部又具备一个Role集合。
找到aside.jsp
<li> <!--这里的地址做一个修改-->
<a href="${pageContext.request.contextPath}/user/list">
<i class="fa fa-circle-o"></i> 用户管理
</a>
</li>
创建 UserController 类
package com.lyh.controller;
import com.lyh.domain.User;
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(){
List<User> userList=userService.list();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userList",userList);
modelAndView.setViewName("user-list"); //返回的视图
return modelAndView;
}
}
创建UserService接口
package com.lyh.service;
import com.lyh.domain.User;
import java.util.List;
public interface UserService {
List<User> list();
}
创建UserServiceImpl
package com.lyh.service.impl;
import com.lyh.domain.User;
import com.lyh.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> list() {
return userDao.findAll();
}
}
创建UserDao接口
package com.lyh.dao;
import com.lyh.domain.User;
import java.util.List;
public interface UserDao {
List<User> findAll();
}
创建UserDaoImpl类
package com.lyh.dao.impl;
import com.lyh.dao.UserDao;
import com.lyh.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;
}
@Override
public List<User> findAll() {
List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
return userList;
}
}
将User的Dao 和User的Service在Spring的配置文件applicationContext.xml中进行相应的配置。
<!-- 配置UserService-->
<bean id="userService" class="com.lyh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<!-- 配置UserDao-->
<bean id="userDao" class="com.lyh.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
找到 user-list.jsp 展示页面,引入jstl
<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
<%--对它进行for循环--%>
<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>
<!-- 这里仅是查询的User对象 在进行实体封装时 Role对象是空的 -->
<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>
测试效果:
Spring练习-用户列表展示2
为当前某一个用户去查询它具备的角色
实际上这个功能,在任何一层上去完成都行,但是现在是在 Service层上去完成。
因为Dao层只负责比较简单的数据库的查询,
Service层才负责复杂的业务
UserServiceImpl类中的代码
package com.lyh.service.impl;
import com.lyh.dao.RoleDao;
import com.lyh.dao.UserDao;
import com.lyh.domain.Role;
import com.lyh.domain.User;
import com.lyh.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;
}
@Override
public List<User> list() {
List<User> userList = userDao.findAll();
//封装 userList中的每一个User的roles数据
//根据主键id 去查找 两张表 一个是 user_role表,一个是role表
for (User user : userList) {
//获得user的id
Long id = user.getId();
//将id作为参数 查询当前userId 对应 的Role集合数据
//现在是查找 Role
List<Role> roles=roleDao.findRoleByUserId(id);
//得到数据之后,用当前 user进行封装
user.setRoles(roles);
//这样循环结束之后,集合当中每个User对象 当中的 roles就有数据了
}
//再次返回就有数据了
return userList;
}
}
applicationContext.xml文件中的 userService 再次进行配置。
!-- 配置UserService-->
<bean id="userService" class="com.lyh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="roleDao" ref="roleDao"/>
</bean>
RoleDao类中
package com.lyh.dao;
import com.lyh.domain.Role;
import java.util.List;
public interface RoleDao {
public List<Role> findAll();
void save(Role role);
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>
<%--对它进行for循环--%>
<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>
</tbody>
效果:
没有问题
Spring练习-用户添加操作-添加页面展示
角色有对应的表进行维护
需要从表中查询完之后,在页面进行相应的展示
点击“新建”不能直接跳转页面了
点击“新建”时,去访问UserController中的方法。
最终返回的是 用户角色 ,角色在页面上进行一个动态展示。
找到“新建”按钮的代码,修改 点击“新建”跳转到的地址。
<!--带UI的只会跳转到保存的页面-->
<button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/user/saveUI'">
<i class="fa fa-file-o"></i> 新建
</button>
UserController中新添加的相关代码
@Autowired
private RoleService roleService;
@RequestMapping("/saveUI")
public ModelAndView saveUI(){
ModelAndView modelAndView = new ModelAndView();
//需要当前所有的角色数据,角色数据 需要RoleService 去 负责
List<Role> roleList = roleService.list();
modelAndView.addObject("roleList",roleList);
//跳转到 添加页面
modelAndView.setViewName("user-add");
return modelAndView;
}
在页面当中需要把数据进行动态的展示
找到 user-add.jsp 页面
添加:标签库
<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
user-add.jsp中的 相关代码
<div class="col-md-2 title">用户角色</div>
<div class="col-md-10 data">
<c:forEach items="${roleList}" var="role">
<%-- 这里可能有多个值 所以roleIds--%>
<input class="" type="checkbox" name="roleIds" value="${role.id}">${role.roleName}
</c:forEach>
</div>
效果:
成功!
Spring练习-用户添加操作-添加数据到数据库
user-add.jsp文件
<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">
<!--这个名字要和当前实体的属性名要一样,这样SpringMVC才能帮我自动封装进去-->
<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">
<%-- 这里可能有多个值 所以roleIds--%>
<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>
UserController类中 添加的内容。
@RequestMapping("/save")
//返回类型是String类型的 重定向到列表页面
public String save(User user,Long[] roleIds){
//执行保存操作
userService.save(user,roleIds);
return "redirect:/user/list";
}
使用这个API,autoGeneratedKeys,是自动生成api的标志,是自动生成还是不自动生成。
UserDaoImpl类中更改的方法
@Override
public Long save(User user) { //主键 是 自动生成的 写成null就行
//jdbc模板有一个API可以帮助我们去返回最终自动生成的id
//创建PreparedStatementCreator new接口 实现未实现的 方法
PreparedStatementCreator creator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { //返回 生成的主键
//使用原始的jdbc 完成 PreparedStatement 的组建 PreparedStatement.RETURN_GENERATED_KEYS 表示数字,值是1,写成1也是可以的
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);//主键 是 自动生成的
preparedStatement.setObject(2,user.getUsername());
preparedStatement.setObject(3,user.getEmail());
preparedStatement.setObject(4,user.getPassword());
preparedStatement.setObject(5,user.getPhoneNum());
return preparedStatement;
}
};
//创建KeyHolder
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
//会通过这个keyHolder获得生成的主键
jdbcTemplate.update(creator,keyHolder);
//获得生成的主键
long userId = keyHolder.getKey().longValue();
return userId; //返回当前保存用户的id 该id是数据库自动生成的
}
测试:
数据库中:
Service层去执行Dao层的多条sql时,多个操作时得有事务的控制
Spring练习-删除用户的操作
点击“删除”把要删除用户的id传递到后台。
最终要删除的表是:以下两个表格的内容
删除掉表格的时候,得先删除掉 sys_user_role 的表格,因为这个是从表
而 sys_user 表格是主表
先删除sys_user表格,是执行不成功的,因为有**外键约束,**所以得先删除sys_user_role表格。
在user-list.jsp文件中找到“删除”的位置。
<%--对它进行for循环--%>
<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">
<%-- 把当前的id传递进去--%>
<a onclick="delUser('${user.id}')" href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
</td>
</tr>
</c:forEach>
<script>
function delUser(userId) {
if(confirm("您确认要删除吗?")){
location.href="${pageContext.request.contextPath}/user/del/"+userId;
}
}
</script>
controller层代码:
@RequestMapping("/del/{userId}")
public String del(@PathVariable("userId") Long userId){
userService.del(userId);
//删除完毕之后,还是跳转到列表页面
return "redirect:/user/list";
}
UserService接口中的代码:
public interface UserService {
List<User> list();
void save(User user, Long[] roleIds);
void del(Long userId);
}
UserServiceImpl中的代码:
@Override
public void del(Long userId) {
//1、删除sys_user_role关系表
userDao.delUserRoleRel(userId);
//2、删除sys_user表格
userDao.del(userId);
}
UserDao接口中的代码
package com.lyh.dao;
import com.lyh.domain.User;
import java.util.List;
public interface UserDao {
List<User> findAll();
Long save(User user);
void saveUserRoleRel(Long id, Long[] roleIds);
void delUserRoleRel(Long userId);
void del(Long userId);
}
UserDaoImpl 中的代码
@Override
public void delUserRoleRel(Long userId) {
jdbcTemplate.update("delect from sys_user_role where userId=?",userId);
}
@Override
public void del(Long userId) {
jdbcTemplate.update("delect from sys_user where id=?",userId);
}
效果:
lisi用户的数据已经被删除
数据库中:lisi 的信息已经被删除
但是:UserServiceImpl类中,一个删除操作中有两个具体的数据库操作
如果
第一个执行数据库操作的方法执行成功了
第二个执行数据库操作的方法执行失败了
目前的写法中
也没有同时成功或者同时失败
像业务层一套的操作都应该具备事务性。
@Override
public void del(Long userId) {
//1、删除sys_user_role关系表
userDao.delUserRoleRel(userId);
//2、删除sys_user表格
userDao.del(userId);
}