需求:使用ssm框架完成对account表的增删改查操作。
1.确定数据库 和表
CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `spring_db`;
/*Table structure for table `account` */
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `account` */
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000),(2,'jerry',1000);
2.创建web模块,导入相关坐标:
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.1.15
org.mybatis
mybatis
3.5.1
org.projectlombok
lombok
1.18.10
junit
junit
4.12
Account实体
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
private Integer id;
private String name;
private Double money;
}
AccountDao接口和映射
public interface AccountDao {
public List findAll();
}
同时在resources资源里面创建mybaits相关的AccountDao.xml文件
SqlMapConfig.xml配置
测试:
public class MyBatisTest {
@Test
public void test01() throws Exception {
// 1.加载核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2.构建工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 3.创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4.创建代理对象
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
// 5.查询
List list = accountDao.findAll();
for (Account account : list) {
System.out.println(account);
}
// 6.释放资源
sqlSession.close();
}
}
此时搭建MyBatis环境完毕
1.导入spring坐标
org.springframework
spring-context
5.1.5.RELEASE
org.aspectj
aspectjweaver
1.9.5
org.springframework
spring-jdbc
5.1.5.RELEASE
org.springframework
spring-test
5.1.5.RELEASE
2.AccountService接口和实现
public interface AccountService {
List findAll();
}
@Service
public class AccountServiceImpl implements AccountService {
@Override
public List findAll() {
System.out.println("AccountServiceImpl执行了...");
return null;
}
}
3.applicationContext.xml配置
测试:
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void test01()throws Exception{
List list = accountService.findAll();
}
}
思想:
原来我们使用mybatis框架,需要手动创建 sqlSessionFactory 、 sqlSession 、accountDao代理对象,被spring整合后,这些对象的创建权都交给ioc容器,我们的service层就可以直接使用@Autowired 完成依赖注入,整合就搞定了
MyBatis分析:
整合:
1.导入整合坐标:
org.mybatis
mybatis-spring
1.3.2
修改AccountService实现
@Service
public class AccountServiceImpl implements AccountService {
// 依赖AccountDao
@Autowired
private AccountDao accountDao;
@Override
public List findAll() {
return accountDao.findAll();
}
}
测试:
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void test01()throws Exception{
List list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
}
}
测试通过:
总结:
导入springMVC坐标
org.springframework
spring-webmvc
5.1.5.RELEASE
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
jstl
jstl
1.2
导入相关页面资源:
web.xml
前端控制器,中文过滤器
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
4
springmvc
*.do
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encodingFilter
/*
spring-mvc.xml
AccountController和list.jsp页面
@RequestMapping(value = "/account", name = "账户模块")
public class AccountController {
@RequestMapping(value = "/findAll", name = "查询账户列表")
public String findAll(Model model) {
// 模拟service,提供假数据...
List list = new ArrayList<>();
list.add(new Account(1, "jack", 200d));
list.add(new Account(2, "lucy", 100d));
list.add(new Account(3, "lufei", 200d));
list.add(new Account(4, "james", 3000d));
model.addAttribute("list", list);
return "/list.jsp"; // 使用默认视图解析器
}
}
访问测试:在index.jsp配置:
然后进行tomcat部署即可测试成功
思想:
springMVC和spring本身就是同一家公司,不需要编写任何整合代码,可以做到无缝对接....
虽然不需要写任何整合代码,但是web.xml 只加载了(DispatcherServlet)前端控制器,扫描了 spring-mvc.xml配置文件,并没有去加载 applicationContext.xml配置文件,所以web层无法依赖注入service层代码...
我们现在需要在web项目启动时,加载spring环境,那么springMVC就可以从spring容器获得service对象了...
我们这里需要借助一个监听器:ServletContextListener,就可以在web工程启动时,加载spring的环境 applicationContext.xml,初始化spring容器,至此我们的web层就可以注入service层代码了...
spring框架就提供了这个一个监听器,专门加载applicationContext.xml,配置文件... 这里需要导入一个坐标
spring-web
,springMVC的坐标其实已经包含了它
在web.xml中配置监听器:
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
修改AccountController
@Controller
@RequestMapping(value = "/account", name = "账户模块")
public class AccountController {
// 依赖AccountService
@Autowired
private AccountService accountService;
@RequestMapping(value = "/findAll", name = "查询账户列表")
public String findAll(Model model) {
List list = accountService.findAll();
model.addAttribute("list", list);
return "/list.jsp"; // 使用默认视图解析器
}
}
自此,三大框架整合成功了
add.jsp修改
web层
@RequestMapping(value = "/save",name = "添加账户")
public String save(Account account){
accountService.save(account);
return "redirect:/account/findAll.do";
}
service层
dao层:
测试完成即可
方式一:注解方式
applicationContext.xml文件
AccountService实现
(2)xml方式:
list.jsp
web层:
service层:
dao层“
Account findById(Integer id);
update.jsp
修改数据:
update.jsp
web层
service层
dao层
void update(Account account);
一般sql执行方案:
update account set name=#{name},money=#{money} where id=#{id}
动态sql执行方案:
update account
name=#{name},
money=#{money},
where id=#{id}
执行完毕即可成功
list.jsp
AccountController
@RequestMapping(value = "/delete",name = "账户删除")
public String delete(Integer id){
accountService.delete(id);
return "redirect:/account/findAll.do";
}
service
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
dao层
void delete(Integer id);
delete from account where id=#{id}
执行完毕即可
全选与反选:
运行流程:
web层:
service层
dao层:
测试完成成功。
在企业开发中,有的页面需要进行权限控制。
思想:
(1)用户登录
准备user表与数据:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`password`) values (1,'jack','123'),(2,'tom','123');
User实体:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
}
login.jsp
web层
@Controller
@RequestMapping(value = "/user", name = "用户模块")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login", name = "登录功能")
public String login(User user, HttpServletRequest request, HttpSession session) {
User currentUser = userService.login(user);
if (currentUser == null) { // 登录失败
request.setAttribute("error", "用户名或密码错误...");
return "/login.jsp";
}
// 登录成功,跳转到查询列表页面
session.setAttribute("currentUser", currentUser);
return "redirect:/account/findAll.do";
}
}
service层
dao层
login.jsp:显示错误信息
(2)权限拦截:
自定义登录拦截器
/*
登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
// 预处理拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 1.从session中获取登录user对象
User currentUser = (User) request.getSession().getAttribute("currentUser");
// 2.判断
if(currentUser == null){
try {
// 重定向到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
} catch (IOException e) {
e.printStackTrace();
}
// 未登录,拦截
return false;
}
// 已登录放行
return true;
}
}
在spring-mvc.xml中配置拦截器规则
我们使用的spring框架,通过ContextLoaderListener加载的spring容器(父容器)
我们使用的springMVC框架,通过DispatcherServlet加载springMVC容器(子容器)
ssm配置的总结项:
项目整体架构:
pom.xml
4.0.0
com.wsl
springday08_mybatis_spring_springMVC
1.0-SNAPSHOT
war
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.1.15
org.mybatis
mybatis
3.5.1
org.projectlombok
lombok
1.18.10
junit
junit
4.12
org.springframework
spring-context
5.1.5.RELEASE
org.aspectj
aspectjweaver
1.9.5
org.springframework
spring-orm
5.1.5.RELEASE
org.springframework
spring-jdbc
5.1.5.RELEASE
org.springframework
spring-test
5.1.5.RELEASE
org.mybatis
mybatis-spring
1.3.2
org.springframework
spring-webmvc
5.1.5.RELEASE
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
jstl
jstl
1.2
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
UTF-8
web.xml文件
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
4
springmvc
*.do
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encodingFilter
/*
SqlMapConfig.xml
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
spring-mvc.xml
applicationContext.xml
AccountController
@Controller
@RequestMapping(value = "/account",name = "账户模块")
public class AccountController {
@Autowired
AccountService accountService;
@RequestMapping(value = "/findAll",name = "查询账户列表")
public String findAll(Model model){
// List list = new ArrayList<>();
// list.add(new Account(1,"javak",2000d));
// list.add(new Account(2,"abc",2600d));
// list.add(new Account(3,"ecd",600d));
// list.add(new Account(4,"edd",1200d));
// list.add(new Account(5,"tom",4300d));
// list.add(new Account(6,"c++",3200d));
// model.addAttribute("list",list);
List list = accountService.findAll();
model.addAttribute("list",list);
return "/list.jsp";
}
@RequestMapping(value = "/save",name = "添加账户")
public String save(Account account){
accountService.save(account);
return "redirect:/account/findAll.do";
}
@RequestMapping(value = "/findById",name = "查询账户")
public String findById(Integer id, Model model){
Account account = accountService.findById(id);
model.addAttribute("account",account);
return "/update.jsp";
}
@RequestMapping(value = "/update",name = "更新账户")
public String update(Account account){
accountService.update(account);
return "redirect:/account/findAll.do";
}
@RequestMapping(value = "/delete",name = "账户删除")
public String delete(Integer id){
accountService.delete(id);
return "redirect:/account/findAll.do";
}
@RequestMapping(value = "/deleteBath",name = "批量删除")
public String deleteBath(Integer[] ids){
accountService.deleteBath(ids);
return "redirect:/account/findAll.do";
}
}