最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

今日聚焦!SSM整合(spring-springmvc-mybatis)之CRUD

来源:博客园

概述:

加入功能:CRUD、分页、返回json、国际化

配置了访问静态文件;


(资料图片)

配置了REST 风格的代码;

一、目录结构:

目录:

jar包说明:

spring核心jar包:

  1. commons-logging-1.2.jar
  2. spring-beans-5.3.10.jar
  3. spring-context-5.3.10.jar
  4. spring-core-5.3.10.jar
  5. spring-expression-5.3.10.jar

spring aop:

  1. spring-aop-5.3.10.jar
  2. spring-aspects-5.3.10.jar

springmvc jar包:

  1. spring-web-5.3.10.jar
  2. spring-webmvc-5.3.10.jar

spring 数据库交互jar包:

  1. spring-jdbc-5.3.10.jar
  2. spring-tx-5.3.10.jar

mybatis jar包:

  1. mybatis-3.5.9.jar
  2. mysql-connector-java-8.0.27 (1).jar
  3. log4j-1.2.17.jar

mybatis-spring 适配器包:

  1. mybatis-spring-1.3.2.jar

c3po:

  1. c3p0-0.9.5.5.jar
  2. mchange-commons-java-0.2.19.jar

jstl:

  1. standard.jar
  2. jstl.jar

jackson(目的是返回json):

  1. jackson-annotations-2.9.10.jar
  2. jackson-core-2.9.10.jar
  3. jsqlparser-4.3.jar

mybatis 分页:

  1. jsqlparser-4.3.jar
  2. pagehelper-5.3.0.jar

二、java源代码

实体类:

普通实体类可以继承通用类,通用类提供了分页所需要的字段;原因是mybatis分页插件pageHelper的使用,这里采用了参数对象分页。所以需要在对象中提供分页字段,比如:pageNum、pageSize、orderBy;

通用类CommonEntity.java:

1 package ssm.entity; 2  3 public class CommonEntity { 4     private Integer pageNum; 5     private Integer pageSize; 6     private String orderBy = "id desc"; 7  8     public Integer getPageNum() { 9         return pageNum;10     }11 12     public void setPageNum(Integer pageNum) {13         this.pageNum = pageNum;14     }15 16     public Integer getPageSize() {17         return pageSize;18     }19 20     public void setPageSize(Integer pageSize) {21         this.pageSize = pageSize;22     }23 24     public String getOrderBy() {25         return orderBy;26     }27 28     public void setOrderBy(String orderBy) {29         this.orderBy = orderBy;30     }31 32 }
View Code

实体类:Employee.java:

package ssm.entity;public class Employee extends CommonEntity {    private Integer id;    private String lastName;    private String email;    private String gender;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getLastName() {        return lastName;    }    public void setLastName(String lastName) {        this.lastName = lastName;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getGender() {        return gender;    }    public void setGender(String gender) {        this.gender = gender;    }    @Override    public String toString() {        return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";    }}
View Code

Controller部分:

1 package ssm.controller; 2  3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.PathVariable; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestMethod; 8 import org.springframework.web.bind.annotation.ResponseBody; 9 import org.springframework.web.servlet.ModelAndView;10 11 import com.github.pagehelper.PageInfo;12 13 import ssm.entity.Employee;14 import ssm.service.EmployeeService;15 16 /**17  * @author lixiuming18  * @Description19  * @Date 2022年3月29日下午3:38:0620  */21 @RequestMapping("/emp")22 @Controller23 public class EmployeeController {24     @Autowired25     private EmployeeService employeeService;26 27     /**28      * 列表页面29      * 30      * @param employee31      * @return32      */33     @RequestMapping("/list")34     public ModelAndView list(Employee employee) {35         ModelAndView mv = new ModelAndView("index");36         PageInfo list = employeeService.list(employee);37         mv.addObject("pages", list);38         return mv;39     }40 41     /**42      * 添加页面43      * 44      * @return45      */46     @RequestMapping("/add")47     public ModelAndView add() {48         ModelAndView mv = new ModelAndView("update");49         return mv;50     }51 52     /**53      * 编辑页面54      * 55      * @param id56      * @return57      */58     @RequestMapping(value = "/edit/{id}")59     public ModelAndView edit(@PathVariable(name = "id", required = false) Integer id) {60         Employee employee = employeeService.getEmpById(id);61         ModelAndView mv = new ModelAndView("update");62         mv.addObject("employee", employee);63         return mv;64     }65 66     /**67      * 添加/编辑68      * 69      * @param employee70      * @return71      */72     @ResponseBody73     @RequestMapping(value = "/update", method = RequestMethod.POST)74     public String update(Employee employee) {75         System.out.println(employee);76         return employeeService.update(employee);77     }78 79     /**80      * 详情81      * 82      * @param id83      * @return84      */85     @ResponseBody86     @RequestMapping(value = "/detail", method = RequestMethod.POST)87     public Employee update(Integer id) {88         return employeeService.getEmpById(id);89     }90 91 }
View Code

Service部分:

service接口:

1 package ssm.service; 2  3 import com.github.pagehelper.PageInfo; 4  5 import ssm.entity.Employee; 6  7 /** 8  *  9  * @author lixiuming10  * @Description11  * @Date 2022年3月29日下午3:46:3312  */13 public interface EmployeeService {14 15     /**16      * 根据ID获取实体17      * 18      * @param id19      * @return20      */21     Employee getEmpById(Integer id);22 23     /**24      * 获取列表页面25      * 26      * @param employee27      * @return28      */29     PageInfo list(Employee employee);30 31     /**32      * 添加/修改33      * 34      * @param employee35      * @return36      */37     String update(Employee employee);38 39 }
View Code

serviceImple实现类:

1 package ssm.service; 2  3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Service; 5  6 import com.github.pagehelper.PageInfo; 7  8 import ssm.entity.Employee; 9 import ssm.mapper.EmployeeMapper;10 11 @Service("employeeService")12 public class EmployeeServiceImpl implements EmployeeService {13 14     @Autowired15     private EmployeeMapper employeeMapper;16 17     @Override18     public Employee getEmpById(Integer id) {19         return employeeMapper.getEmpById(id);20     }21 22     @Override23     public PageInfo list(Employee employee) {24         return employeeMapper.list(employee);25     }26 27     @Override28     public String update(Employee employee) {29         if (employee.getId() != null && employee.getId() > 0) {30             employeeMapper.update(employee);31         } else {32             employeeMapper.insert(employee);33         }34         return "200";35     }36 37 }
View Code

Mapper部分:

1 package ssm.mapper; 2  3 import com.github.pagehelper.PageInfo; 4  5 import ssm.entity.Employee; 6  7 /** 8  *  9  * @author lixiuming10  * @Description11  * @Date 2022年3月29日下午3:48:4512  */13 public interface EmployeeMapper {14 15     /**16      * 根据id 获取 实体对象17      * 18      * @param id19      * @return20      */21     Employee getEmpById(Integer id);22 23     /**24      * 获取页面25      * 26      * @param employee27      * @return28      */29     PageInfo list(Employee employee);30 31     /**32      * 插入数据33      * 34      * @param employee35      */36     void insert(Employee employee);37 38     /**39      * 修改40      * 41      * @param employee42      */43     void update(Employee employee);44 }
View Code

sql语句:

1  2  5  6  7      8     12     13     17     18     19         insert into tbl_employee20         (last_name,email,gender) values(21         #{lastName,jdbcType=VARCHAR},22         #{email,jdbcType=VARCHAR},23         #{gender,jdbcType=VARCHAR}24 25         )26     27     28     29         update tbl_employee set30         last_name=#{lastName,jdbcType=VARCHAR},email=#{email,jdbcType=VARCHAR},gender=#{gender,jdbcType=VARCHAR}31         where id=#{id,jdbcType=INTEGER}32     33 
View Code

数据转换:

StringToDateConverter, 把String 转为日期;

应用场景:form表单提交日期到后台,由于传输的数据时String类型的日期,而后台对应的字段为java.util.Date类型;如果需要实现后台传入的数据自动转成对应的java.util.Date类型的字段则需要配置配置数据转换;转换类如下:

1 package ssm.convert; 2  3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5  6 import org.springframework.core.convert.converter.Converter; 7  8 public class StringToDateConverter implements Converter { 9 10     // 日期类型模板:如yyyy-MM-dd,通过配置时注入11     private String datePattern;12 13     public void setDatePattern(String datePattern) {14         this.datePattern = datePattern;15     }16 17     // Converter接口的类型转换方法18     @Override19     public Date convert(String date) {20         try {21             SimpleDateFormat dateFormat = new SimpleDateFormat(this.datePattern);22             // 将日期字符串转换成Date类型返回23             return dateFormat.parse(date);24         } catch (Exception e) {25             e.printStackTrace();26             System.out.println("日期转换失败!");27             return null;28         }29 30     }31 32 }
View Code

StringToIntegerConverter,把String转成Integer

1 package ssm.convert; 2  3 import org.springframework.core.convert.converter.Converter; 4  5 public class StringToIntegerConverter implements Converter { 6  7     // Converter接口的类型转换方法 8     @Override 9     public Integer convert(String intData) {10         try {11             // 将日期字符串转换成Date类型返回12             return Integer.valueOf(intData);13         } catch (Exception e) {14             e.printStackTrace();15             System.out.println("整型转换失败");16             return null;17         }18 19     }20 21 }
View Code

分页类:

参考地址:https://github.com/xjs1919/PageHelperExt

PageObjectFactory.java

1 package ssm.utils; 2  3 import org.apache.ibatis.reflection.factory.DefaultObjectFactory; 4  5 import com.github.pagehelper.PageInfo; 6  7 /** 8  * Created by xujiashuai on 2016/6/29. 9  */10 public class PageObjectFactory extends DefaultObjectFactory {11 12     private static final long serialVersionUID = 3963031299778136554L;13 14     /**15      * 如果类型为page的话让其也判断为集合16      */17     public  boolean isCollection(Class type) {18         if (type == PageInfo.class) {19             return true;20         }21         return super.isCollection(type);22     }23 24     @SuppressWarnings({ "unchecked", "rawtypes" })25     public  T create(Class type) {26         if (type == PageInfo.class) {27             return (T) new PageInfo();28         }29         return create(type, null, null);30     }31 }
View Code

PageObjectWrapper.java

1 package ssm.utils;  2   3 import java.util.List;  4   5 import org.apache.ibatis.reflection.MetaObject;  6 import org.apache.ibatis.reflection.factory.ObjectFactory;  7 import org.apache.ibatis.reflection.property.PropertyTokenizer;  8 import org.apache.ibatis.reflection.wrapper.ObjectWrapper;  9  10 import com.github.pagehelper.Page; 11 import com.github.pagehelper.PageInfo; 12  13 public class PageObjectWrapper implements ObjectWrapper { 14  15     @SuppressWarnings("rawtypes") 16     private PageInfo pageinfo; 17  18     @SuppressWarnings("rawtypes") 19     public PageObjectWrapper(PageInfo wrapped) { 20         this.pageinfo = wrapped; 21     } 22  23     @SuppressWarnings({ "rawtypes", "unchecked" }) 24     @Override 25     public  void addAll(List element) { 26         Page page = (Page) element; 27         pageinfo.setPageNum(page.getPageNum()); 28         pageinfo.setPageSize(page.getPageSize()); 29         pageinfo.setPages(page.getPages()); 30         pageinfo.setList(page); 31         pageinfo.setSize(page.size()); 32         pageinfo.setTotal(page.getTotal()); 33         if (page.size() == 0) { 34             pageinfo.setStartRow(0); 35             pageinfo.setEndRow(0); 36         } else { 37             pageinfo.setStartRow(page.getStartRow() + 1); 38             pageinfo.setEndRow(pageinfo.getStartRow() - 1 + pageinfo.getSize()); 39         } 40         pageinfo.setNavigatePages(5); 41         calcNavigatepageNums(pageinfo, page); 42         calcPage(pageinfo); 43         judgePageBoudary(pageinfo); 44     } 45  46     @SuppressWarnings("rawtypes") 47     private void calcNavigatepageNums(PageInfo pageinfo, com.github.pagehelper.Page page) { 48         int pages = pageinfo.getPages(); 49         int navigatePages = pageinfo.getNavigatePages(); 50         int pageNum = pageinfo.getPageNum(); 51         int[] navigatepageNums = null; 52         if (pages <= navigatePages) { 53             navigatepageNums = new int[pages]; 54             for (int i = 0; i < pages; i++) { 55                 navigatepageNums[i] = i + 1; 56             } 57         } else { 58             navigatepageNums = new int[navigatePages]; 59             int startNum = pageNum - navigatePages / 2; 60             int endNum = pageNum + navigatePages / 2; 61  62             if (startNum < 1) { 63                 startNum = 1; 64                 for (int i = 0; i < navigatePages; i++) { 65                     navigatepageNums[i] = startNum++; 66                 } 67             } else if (endNum > pages) { 68                 endNum = pages; 69                 for (int i = navigatePages - 1; i >= 0; i--) { 70                     navigatepageNums[i] = endNum--; 71                 } 72             } else { 73                 for (int i = 0; i < navigatePages; i++) { 74                     navigatepageNums[i] = startNum++; 75                 } 76             } 77         } 78         pageinfo.setNavigatepageNums(navigatepageNums); 79     } 80  81     @SuppressWarnings("rawtypes") 82     private void calcPage(PageInfo pageinfo) { 83         int[] navigatepageNums = pageinfo.getNavigatepageNums(); 84         int pageNum = pageinfo.getPageNum(); 85         if (navigatepageNums != null && navigatepageNums.length > 0) { 86             if (pageNum > 1) { 87                 pageinfo.setPrePage(pageNum - 1); 88             } 89             if (pageNum < pageinfo.getPages()) { 90                 pageinfo.setNextPage(pageNum + 1); 91             } 92         } 93     } 94  95     @SuppressWarnings("rawtypes") 96     private void judgePageBoudary(PageInfo pageinfo) { 97         int pageNum = pageinfo.getPageNum(); 98         int pages = pageinfo.getPages(); 99         pageinfo.setIsFirstPage(pageNum == 1);100         pageinfo.setIsLastPage(pageNum == pages);101         pageinfo.setHasPreviousPage(pageNum > 1);102         pageinfo.setHasNextPage(pageNum < pages);103     }104 105     @Override106     public Object get(PropertyTokenizer prop) {107         return null;108     }109 110     @Override111     public void set(PropertyTokenizer prop, Object value) {112 113     }114 115     @Override116     public String findProperty(String name, boolean useCamelCaseMapping) {117         return null;118     }119 120     @Override121     public String[] getGetterNames() {122         return new String[0];123     }124 125     @Override126     public String[] getSetterNames() {127         return new String[0];128     }129 130     @Override131     public Class getSetterType(String name) {132         return null;133     }134 135     @Override136     public Class getGetterType(String name) {137         return null;138     }139 140     @Override141     public boolean hasSetter(String name) {142         return false;143     }144 145     @Override146     public boolean hasGetter(String name) {147         return false;148     }149 150     @Override151     public MetaObject instantiatePropertyValue(String name, PropertyTokenizer prop, ObjectFactory objectFactory) {152         return null;153     }154 155     @Override156     public boolean isCollection() {157         return false;158     }159 160     @Override161     public void add(Object element) {162 163     }164 }
View Code

PageObjectWrapperFactory.java

1 package ssm.utils; 2  3 import org.apache.ibatis.reflection.MetaObject; 4 import org.apache.ibatis.reflection.ReflectionException; 5 import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; 6 import org.apache.ibatis.reflection.wrapper.ObjectWrapper; 7  8 import com.github.pagehelper.PageInfo; 9 10 /**11  * Created by xujiashuai on 2016/6/29.12  */13 public class PageObjectWrapperFactory extends DefaultObjectWrapperFactory {14 15     @Override16     public boolean hasWrapperFor(Object object) {17         if (object instanceof PageInfo) {18             return true;19         }20         return false;21     }22 23     @SuppressWarnings("rawtypes")24     @Override25     public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {26         if (object instanceof PageInfo) {27             return new PageObjectWrapper((PageInfo) object);28         }29         throw new ReflectionException(30                 "The DefaultObjectWrapperFactory should never be called to provide an ObjectWrapper.");31     }32 }
View Code

页面:

index.jsp

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 4 <%@taglib prefix="s" uri="http://www.springframework.org/tags"%> 5  6  7  8 <script type="text/javascript" src="/js/jquery.min.js"></script> 9 10 <s:message code="EMPLOYEE.LIST"></s:message>11 12 13 14     15         16             17             18             19             20             21         22         23             24                 25                 26                 27                 28                 31                 34                 35             36         37     
id
${item.id}${item.lastName}${item.email}${item.gender} " class="editRow">29 30 " class="detailRow">32 33
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 58

59 60 <script>61 $(function() {62 $(".page").each(function() {63 $(this).click(function() {64 var pageNum = $(this).next().val();65 var pageSize = 5;66 window.location = "${pageContext.request.contextPath}/emp/list?pageNum="67 + pageNum68 + "&pageSize="69 + pageSize;70 })71 });72 $("#add").click(function(){73 window.location = "${pageContext.request.contextPath}/emp/add"74 })75 $(".editRow").each(function(){76 $(this).click(function(){77 var id = $(this).next().val();78 window.location = "edit/"+id79 })80 })81 $(".detailRow").each(function(){82 $(this).click(function(){83 var id = $(this).next().val();84 $.post("/emp/detail",{id:id},function(data){85 alert("姓名:"+data.lastName+",邮箱:"+data.email+",性别:"+data.gender);86 })87 88 })89 })90 91 })92 </script>93
View Code

update.jsp

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4     <%@ taglib prefix="s" uri="http://www.springframework.org/tags" %> 5  6  7  8 <script src="/js/jquery.min.js"></script> 9 10 <s:message code="EMPLOYEE.EDIT"></s:message>11 12 13 
14
15
16 :男
17 18 ">19
20 21 <script>22 $(function(){23 var gender = "${employee.gender}";24 if(!!gender ){25 if(gender == "男"){26 $("input:radio[name="gender"]:first").attr("checked","checked");27 }28 if(gender == "女"){29 $("input:radio[name="gender"]:last").attr("checked","checked");30 }31 }32 33 })34 </script>35
View Code

三、配置

web.xml配置:

DispatcherServlet(分发器)配置 +ContextLoaderListener整合spring配置+CharacterEncodingFilter请求/响应编码配置;

1  2  6      7         CharacterEncodingFilter 8         org.springframework.web.filter.CharacterEncodingFilter 9         10         11             encoding12             utf-813         14     15     16         CharacterEncodingFilter17         /*18     19     20         contextConfigLocation21         classpath:spring.xml22     23     24         org.springframework.web.context.ContextLoaderListener25     26     27     28         springDispatcherServlet29         org.springframework.web.servlet.DispatcherServlet30         31         33         34             contextConfigLocation35             classpath:springmvc.xml36         37         38         139     40 41     42     43         springDispatcherServlet44         /45     46 
View Code

如果需要使用put,delete的请求,还需要配置:这个例子中没有这一段;具体教程请看REST( Representational State Transfer )

1     2         HiddenHttpMethodFilter3         org.springframework.web.filter.HiddenHttpMethodFilter4     5     6         HiddenHttpMethodFilter7         /*8     

springmvc配置:

springmvc 只负责网站跳转逻辑;

springmvc.xml:

  • spring数据转换:配置了String转 java.util.Date ,实现类是StringToDateConverter;配置了 String 转Integer ,实现类是StringToIntegerConverter完成后需要加到中;
  • 的作用是可以访问到静态文件,比如访问js;如果没有这个配置,页面无法引用js;

参考:https://www.cnblogs.com/lixiuming521125/p/16011536.html

1  2  9 10     11     12     14         16         18     19     20     22         23         24     25 26 27     28     30         31             32                 33                     34                 35                 36                 37             38         39     40 41     42     44     45 46     47     48 49     50     52         53     54 55 56 

spring配置:

spring 希望管理所有的业务逻辑组件,等

spring.xml:

1  2 11 12     13 14     15     17         19         21     22 23     24     25     27     28     30         31         32         33         34     35     36     38         39     40     41     43 44     46     47     49         50        51         53        54         56         57             58                 59                     60                         61                         62                             helperDialect=mysql63                             reasonable=true64                             supportMethodsArguments=true65                             params=count=countSql66                             autoRuntimeDialect=true67                         68                     69                 70             71         72     73     74     76         78         79     80     81     83     84 

mybatis-config.xml配置:

1  2  5  6      7      8          9         10         11         12         13         14         15     16     18 19     21 22     24         

dbconfig.properties:

1 jdbc.driver=com.mysql.jdbc.Driver2 jdbc.url=jdbc:mysql://localhost:3306/mybatis3 jdbc.username=root4 jdbc.password=5 6 jdbc2.driver=com.mysql.jdbc.Driver7 jdbc2.url=jdbc:mysql://localhost:3306/mybatis28 jdbc2.username=root9 jdbc2.password=
View Code

i18n_zh_CN.properties

1 EMPLOYEE.LASTNAME=姓名 2 EMPLOYEE.EMAIL=邮箱 3 EMPLOYEE.GENDER=性别 4 EMPLOYEE.LIST=列表 5 EMPLOYEE.EDIT=添加/修改 6 SYS.OPERATE=操作 7 SYS.ADD=添加 8 SYS.EDIT=修改 9 SYS.SUBMIT=提交10 SYS.DETAIL=详情
View Code

运行结果:

访问:http://localhost:8080/emp/list?pageNum=1&pageSize=5,显示列表第一页,数据条数为5条;

访问:http://localhost:8080/emp/list?pageNum=2&pageSize=5,显示列表第二页,数据条数为5条;

目前是id 倒叙的,也可以自定义排序规则;比如:http://localhost:8080/emp/list?pageNum=2&pageSize=5&orderBy=id%20asc,lastName%20asc;

点击添加跳转到跳转页面;点击修改操作,显示修改页面;

点击详情alert弹出详情;

代码示例地址:

基础班:https://gitee.com/joy521125/ssm-senior-base.git

maven版:https://gitee.com/joy521125/ssm-senior.git

关键词: 配置文件 数据转换 数据转换器