源码地址:https://codechina.csdn.net/wwwzhouzy/zhouzyssm
ssm就是spring+springmvc+mybatis
先来个图:
我们再来看看SpringMVC的流程吧
1、 用户发送请求至前端控制器DispatcherServlet。
2、 DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、 处理器映射器找到具体的处理器,生成处理器对象及处理器拦截器一并返回给DispatcherServlet。
4、 DispatcherServlet调用HandlerAdapter处理器适配器。
5、 HandlerAdapter经过适配调用具体的处理器。
6、 Controller执行完成返回ModelAndView。
7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。
8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器。
9、 ViewReslover解析后返回具体View。
10、DispatcherServlet根据View进行渲染视图。
11、 DispatcherServlet响应用户,DispatcherServlet也是整个Spring MVC的核心,它负责接收HTTP请求组织协调Spring MVC的各个组成部分
先看看项目结构图,有个大概的认知:
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>zzyssm</name> <groupId>com.zhouzy.ssm</groupId> <artifactId>zzyssm</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/ssm</url> <server>tomcat8</server> <path>/ssm</path> </configuration> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <log4j.version>1.2.17</log4j.version> <spring.version>4.3.9.RELEASE</spring.version> <mybatis.version>3.2.2</mybatis.version> </properties> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</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.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.0</version> </dependency> </dependencies> </project>
里面指定了springmvc的配置文件路径、日志配置文件路径和mybatis配置文件路径
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- 监听配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmybatis配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 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:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 过滤器 --> <filter> <filter-name>characterEncoding</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>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- log4j配置 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
注意配置注解扫描的路径、json传输乱码配置和视图解析器的配置
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd "> <context:component-scan base-package="com.zhouzy.ssm.*"/> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean> <mvc:default-servlet-handler/> <!-- json中文乱码 --> <!--解决json 乱码配置--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/view/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="-1" /> </bean> </beans>
此处用的是mysql数据库,注意配置映射文件路径和事务管理器,指定了jdbc配置文件
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd "> <!-- 引入jdbc配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!--dbcp数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClass}" /> <property name="url" value="${jdbc.connectionURL}" /> <property name="username" value="${jdbc.userId}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 配置spring与mybatis结合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zhouzy.ssm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- Spring事务控制(注解配置) --> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 这个必须配置,否则事物不起作用 --> <!-- 支持@Transactional注解支持 --> <!-- 带有@Transactional标记的方法会自动调用txManager管理事务 --> </beans>
主要配置数据库的连接信息
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/zhouzy?useUnicode=true&characterEncoding=utf-8 jdbc.userId=root jdbc.password=123456 #jdbc.driverLocation=E:\\Java\\MySQL\\mysql-connector-java-5.1.43\\mysql-connector-java-5.1.43\\mysql-connector-java-5.1.43-bin.jar ##Oracle 数据库驱动 #jdbc.driver=oracle.jdbc.driver.OracleDriver ##jdbc:mysql://连接地址:端口号(默认3306)/数据库名 #jdbc.url=jdbc:oracle:thin:@10.1.104.xx:1521:xxxx ##用户名 #jdbc.username=lis ##密码 #jdbc.password=hxkf#xxx ##连接池初始化连接 #jdbc.initialSize=10 ##连接池最大连接数 #jdbc.maxActive=100 ##连接池最大空闲连接 #jdbc.maxIdle=0 ##连接池最小空闲连接 #jdbc.minIdle=0 ##等待超时 #jdbc.maxWait=5000 # ##线程池 ##------------ Task ------------ #task.core_pool_size=5 #task.max_pool_size=100 #task.queue_capacity=1000 #task.keep_alive_seconds=60
主要配置日志打印信息
log4j.rootLogger =INFO,DB log4j.logger.sm=INFO,smm log4j.additivity.smm=false log4j.appender.smm = org.apache.log4j.jdbc.JDBCAppender log4j.appender.smm.Driver =com.mysql.jdbc.Driver log4j.appender.smm.URL =jdbc:mysql://localhost:3306/zhouzy log4j.appender.smm.User =root log4j.appender.smm.Password =123456 log4j.appender.smm.Sql = INSERT INTO LOGS(ltid,ltime,userId,lresult,lremark) VALUES('%X{ltid}','%d{yyyy-MM-dd HH:mm:ss}','%X{userId}','%X{lresult}','%X{lremark}')
CREATE TABLE `t_user_info` ( `id` int(11) NOT NULL auto_increment, `name` varchar(50) default NULL, `age` int(11) default NULL, `sex` int(11) default NULL COMMENT '性别:0男 1女', `address` varchar(255) default NULL COMMENT '地址', `mobile` varchar(20) default NULL COMMENT '手机号', `create_time` timestamp NULL default NULL, `update_time` timestamp NULL default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户信息';
可以根据sql在线生成java相关代码,包括mybatis映射文件
地址:http://java.bejson.com/generator
将生成的代码拷贝到对应的地址即可
此处贴部分核心代码:
mapper层:
package com.zhouzy.ssm.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.zhouzy.ssm.model.UserInfo; /** * @description 用户信息表 * @author zhouzhiyao * @date 2021-08-03 */ @Repository public interface UserInfoMapper { /** * 新增 * @author zhouzhiyao * @date 2021/08/03 **/ int insert(UserInfo userInfo); /** * 刪除 * @author zhouzhiyao * @date 2021/08/03 **/ int delete(int id); /** * 更新 * @author zhouzhiyao * @date 2021/08/03 **/ int update(UserInfo userInfo); /** * 查询 根据主键 id 查询 * @author zhouzhiyao * @date 2021/08/03 **/ UserInfo load(int id); /** * 查询 分页查询 * @author zhouzhiyao * @date 2021/08/03 **/ List<UserInfo> pageList(@Param("offset")int offset,@Param("pageSize")int pageSize); /** * 查询 分页查询 count * @author zhouzhiyao * @date 2021/08/03 **/ int pageListCount(); }
service实现类
package com.zhouzy.ssm.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.zhouzy.ssm.mapper.UserInfoMapper; import com.zhouzy.ssm.model.UserInfo; import com.zhouzy.ssm.service.UserInfoService; /** * @description 用户信息表 * @author zhouzhiyao * @date 2021-08-03 */ @Service public class UserInfoServiceImpl implements UserInfoService { @Resource private UserInfoMapper userInfoMapper; public void insert(UserInfo userInfo) { userInfoMapper.insert(userInfo); } public void delete(int id) { userInfoMapper.delete(id); } public void update(UserInfo userInfo) { userInfoMapper.update(userInfo); } public UserInfo load(int id) { return userInfoMapper.load(id); } public Map<String,Object> pageList(int offset, int pagesize) { List<UserInfo> pageList = userInfoMapper.pageList(offset, pagesize); int totalCount = userInfoMapper.pageListCount(); // result Map<String, Object> result = new HashMap<String, Object>(); result.put("data", pageList); result.put("count", totalCount); return result; } }
controller层
package com.zhouzy.ssm.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zhouzy.ssm.model.DataGrid; import com.zhouzy.ssm.model.PageInfo; import com.zhouzy.ssm.model.UserInfo; import com.zhouzy.ssm.service.UserInfoService; @Controller @RequestMapping("/user") public class UserInfoController { @Resource private UserInfoService userInfoService; /** * 新增 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/insert") public void insert(UserInfo userInfo){ userInfoService.insert(userInfo); } /** * 刪除 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/delete") public void delete(int id){ userInfoService.delete(id); } /** * 更新 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/update") public void update(UserInfo userInfo){ userInfoService.update(userInfo); } /** * 查询 根据主键 id 查询 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/load") public Object load(int id){ return userInfoService.load(id); } /** * 查询 分页查询 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/list") public String pageList() { return "user/userList"; } /** * 查询 分页查询 * @author zhouzhiyao * @date 2021/08/03 **/ @RequestMapping("/index") public String index() { return "user/userList"; } /** * 查询 分页查询 * @author zhouzhiyao * @date 2021/08/03 **/ @SuppressWarnings("unchecked") @RequestMapping("/listData") @ResponseBody public String listData(PageInfo page) { int pageNum = page.getPage(); int size = page.getLimit(); Map<String,Object> map = userInfoService.pageList((pageNum-1)*size, size); List<UserInfo> data = (List<UserInfo>)map.get("data"); int count = (Integer)map.get("count"); DataGrid<UserInfo> grid = new DataGrid<UserInfo>(data,count,0,null); return com.alibaba.fastjson.JSONObject.toJSONString(grid); } }
layui表格的对象类
package com.zhouzy.ssm.model; import java.io.Serializable; import java.util.List; public class DataGrid<T> implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private int code; private String msg; private List<T> data; private int count; public DataGrid(){ } public DataGrid(List<T> data,int count,int code,String msg){ this.data = data; this.count = count; this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
分页对象类
package com.zhouzy.ssm.model; public class PageInfo { private int page = 1; private int limit = 20; public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } }
浏览器输入地址:http://localhost:8080/zzyssm
点击用户列表