ssm整合
开发环境ide,mysql数据库,Spring+SpringMVC+Mybatis,tomcat8.5,jdk使用的是1.7版本。
第一步:导入jar包
Spring+ SpringMVC + MyBatis + Mybatis-spring整合包
AOP联盟+织入 + c3p0 数据库连接池 + MySQL连接驱动 + jstl
项目结构如下图:
第二步:创建springmvc.xml文件
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
第三步:在web.xml添加springmvc配置
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
DispatcherServlet
*.do
第四步:配置Controller
第五步:通过Mybatis的逆向工程生成JavaBean/Mapper
简单点说,就是通过数据库中的单表,自动生成java代码。
Mybatis官方提供了逆向工程
可以针对单表自动生成mybatis代码(mapper.javamapper.xmlmodel类)
企业开发中,逆向工程是个很常用的工具
导入jar包,创建generator配置文件
在classpath下,创建generator.xml文件:(文件内容可以从逆向工程的jar包中docs目录下的index.html中找到相关代码)
/p>
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
connectionURL="jdbc:mysql://localhost:3306/mybatisday1"
userId="root"
password="justin">
使用java类来执行逆向工程
public class Main {
public static void main(String[] args) throws Exception {
List warnings = new ArrayList();
boolean overwrite = true;
File configFile = new File("src/generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
}
把生成的代码拷贝到项目中
我是把生成的po类复制到我com.justin.backoffice中的mapper和model中
第六步:修改ItemsMapper.java和ItemsMapper.xml
第七步:定义Service层接口并实现
第八步:配置SqlMappingConfig.xml,我这里给它命名为mybatis.xml,放在config资源路径下
/p>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
第九步:创建Spring的applicationContext.xml
配置数据源和mybatis的session工厂
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://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
第十步:配置c3p0数据源和mybatis的会话工厂
db.properties文件内容,同样是存放在config资源路径下
第十一步:web.xml中配置spring容器
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
第十二步:在applicationContext.xml中添加bean的注解装配
第十三步:ItemsService
第十四步:ItemsController
第十五步:事务配置(在applicationContext.xml中)
第十六步:添加一个保存方法测试事务
service:
public void saveOrUpdate(Items items) {
itemsMapper.insert(items);
}
controller:
@RequestMapping("save")
public String save(){
//创建商品
Items items = new Items();
items.setName("iphonexs");
items.setPrice(8000.00f);
items.setCreatetime(new Date());
items.setDetail("666真好看");
//保存数据
itemsService.saveOrUpdate(items);
return "items/list";
}
接下来对items这个表数据进行增删改查
显示商品数据
package com.justin.backoffice.web.controller;
views/items/list.jsp
删除商品
service:
public void deleteById(Integer id) {
itemsMapper.deleteByPrimaryKey(id);
}
controller:
@RequestMapping("delete")
public String delete(Integer id,Model model){
itemsService.deleteById(id);
return "forward:list.do";
}
显示编辑商品页面
controller:
@RequestMapping("edit")
public String edit(Integer id,Model model){
System.out.println("id:"+id);
//通过id找到商品
Items items = itemsService.findById(id);
if (items!=null){
model.addAttribute("items",items);
}
return "items/edit";
}
views/items/edit.jsp:
名称 | |
价格 | |
描述 | ${items.detail} |
图片 | |
更新商品
需要在页面中隐藏一input标签存id
乱码,在web.xml中配置
EncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
EncodingFilter
/*
controller:
@RequestMapping("update")
public String update(Items items){
System.out.println(items);
//设置时间
items.setCreatetime(new Date());
itemsService.saveOrUpdate(items);
return "forward:list.do";
}
service需要更改一下逻辑:
public void saveOrUpdate(Items items) {
if (items.getId() == null){
itemsMapper.insert(items);
}else{
itemsMapper.updateByPrimaryKeySelective(items);
}
}
文件上传
springmvc.xml配置支持文件上传
views/items/edit.jsp
后台
package com.justin.backoffice.web.controller;
@Controller
@RequestMapping("upload")
public class UploadController {
/**
* 商品图片的上传
*/
@RequestMapping("itemspic")
public void itemspic(HttpServletRequest request, HttpServletResponse response) throws Exception {
//System.out.println(itemspic1);
System.out.println(request);
MultipartHttpServletRequest mutliRequest = (MultipartHttpServletRequest) request;
//1.获取图片数据
MultipartFile mfile = mutliRequest.getFile("itemspic1");
//2.把图片保存在某个路径
//2.1文件保存的文件夹路径
String uploadFolder = request.getServletContext().getRealPath("/upload");
System.out.println("uploadFolder:" + uploadFolder);
File uploadFolderFile = new File(uploadFolder);
if(!uploadFolderFile.exists()){
uploadFolderFile.mkdirs();
}
//2.2.文件
String suffix = mfile.getOriginalFilename().split("\\.")[1];
String fileName = UUID.randomUUID().toString().replace("-","") + "." + suffix;
String totalPath = uploadFolder + "\\" + fileName;
System.out.println("totalpath:" + totalPath);
FileCopyUtils.copy(mfile.getInputStream(),new FileOutputStream(new File(totalPath)));
//返回数据给客户端
String imgURL = "http://localhost:8080/ssm/upload/" + fileName;
String responseJson = "{\"imgUrl\":\"" + imgURL + "\"}";
response.setHeader("content-type","text/json;charset=utf-8");
response.getWriter().write(responseJson);
}
}
文件上传成功啦,如图: