SSM的整合
大家好,我是【1+1=王】, 热爱java的计算机(人工智能)渣硕研究生在读。
如果你也对java、人工智能等技术感兴趣,欢迎关注,抱团交流进大厂!!!
Good better best, never let it rest, until good is better, and better best.近期会重新温习一下SSM的相关知识,相应的博客会更新至专栏【SSM框架】中,欢迎大家关注!
SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html
搭建SSM环境
SSM框架demo工程已上传至github:https://github.com/Bryant6/SSM_Demo.git
创建maven工程
1. File–>New–>Project
**2. 选择Maven工程,并指定JDK,然后添加工程模板。
3. 填写项目名、存储路径、GroupId
4. 指定maven的安装路径、配置文件以及仓库
创建工程结构
引入所需依赖pom.xml
整合SSM的基础依赖如下:
<properties><!-- lib version --><spring.version>5.0.8.RELEASE</spring.version><mybais.version>3.4.6</mybais.version><mybatis-spring.version>1.3.2</mybatis-spring.version><mysql-connector.version>5.1.46</mysql-connector.version><ojdbc7.version>12.1.0.2.0</ojdbc7.version><druid.version>1.0.16</druid.version><aopalliance.version>1.0</aopalliance.version><aspectj.weaver.version>1.6.4.RELEASE</aspectj.weaver.version><commons.logging.version>1.1.1</commons.logging.version><jstl.version>1.2</jstl.version><log4j.version>1.2.16</log4j.version><slf4j-api.version>1.6.1</slf4j-api.version><slf4j-nop.version>1.6.4</slf4j-nop.version><fileupload.version>1.3.1</fileupload.version><jackson.version>2.9.6</jackson.version><junit.version>4.9</junit.version><servlet-api.version>8.5.32</servlet-api.version><jsp-api.version>8.5.32</jsp-api.version><!-- plugins version --><maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version><tomcat7-maven-plugin.version>2.2</tomcat7-maven-plugin.version></properties>
完整的pom.xml见:SSM整合依赖包pom.xml:https://blog.csdn.net/weixin_43598687/article/details/124066660
创建数据库表
创建一个user表。
创建配置文件
MySQL数据库连接信息db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_demo?useUnicoid=true&characterEncoding=UTF8&useSSL=false
jdbc.user=root
jdbc.password=123456
Spring核心配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"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-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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 开启注解扫描 --><context:component-scanbase-package="com.demo.service"/><!-- 配置连接池 --><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost:3306/ssm_demo"/><propertyname="username"value="root"/><propertyname="password"value="123456"/></bean><beanid="sessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/></bean><!-- 配置扫描mapper --><beanid="mapperScannerConfigurer"class="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="sqlSessionFactory"ref="sessionFactory"/><propertyname="basePackage"value="com.demo.mapper"/></bean><!-- 配置事务管理 --><!-- 平台事务管理器 --><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"/></bean><!-- 配置事务通知 --><tx:adviceid="txAdvice"transaction-manager="transactionManager"><tx:attributes><tx:methodname="find"read-only="true"/><tx:methodname="*"/></tx:attributes></tx:advice><!-- 配置事务增强 --><aop:config><aop:advisoradvice-ref="txAdvice"pointcut="execution(public * com.demo.service.*ServiceImpl.*(..))"/></aop:config></beans>
SpringMVC核心配置文件springmvc.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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"><!--开启注解扫描--><context:component-scanbase-package="com.demo.controller"/><!-- 视图解析器 --><beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/views/"/><propertyname="suffix"value=".jsp"/></bean><!-- 异常处理器、文件上传解析器、拦截器、哪些资源不拦截 --><!-- mvc注解支持 --><mvc:annotation-driven/></beans>
mybatis核心配置文件sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 配置环境 --><environmentsdefault="mysql"><environmentid="mysql"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost:3306/ssm_demo"/><propertyname="username"value="root"/><propertyname="password"value="123456"/></dataSource></environment></environments><!-- 引入映射配置文件 --><mappers><packagename="com.demo.mapper"/></mappers></configuration>
日志配置文件log4j.properties
log4j.rootCategory=ERROR, CONSOLE
log4j.logger.com.demo.mapper=DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss} %m %n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%m %n
监听器、过滤器、前端控制器等配置web.xml
<!DOCTYPEweb-appPUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><display-name>Archetype Created Web Application</display-name><!-- 配置监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><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><!-- 配置前端控制器 --><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><!-- 启动加载 --><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
各层类的创建(以插入user为例)
创建User实体类
packagecom.demo.domain;importjava.io.Serializable;publicclassUserimplementsSerializable{privateInteger id;privateString username;privateString password;publicUser(){}publicUser(Integer id,String username,String password){this.id = id;this.username = username;this.password = password;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}@OverridepublicStringtoString(){return"User{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+'}';}}
创建UserMapper【dao层】
UserMapper
public interface UserMapper {
@Insert(value = "insert into user(username,password) values(#{username},#{password})")
void save(User user);
}
创建UserService及实现类UserServiceImpl【service层】
UserService
publicinterfaceUserService{//保存用户voidsave(User user);}
UserServiceImpl
@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserMapper userMapper;@Overridepublicvoidsave(User user){
userMapper.save(user);}}
创建UserController【controller层】
@Controller@RequestMapping("/user")publicclassUserController{@AutowiredprivateUserService userService;@RequestMapping("/save")publicStringsave(User user){System.out.println("controller层:保存账户。。。");
userService.save(user);return"success";}}
创建前端jsp页面
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>Title</title></head><body><h3>成功了</h3></body></html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>Title</title></head><body>
<%-- <h3>用户列表页面</h3>--%>
<%-- <ahref="/user/findAll">查询所有</a>--%>
<h3>测试新增</h3><formaction="/user/save"method="post">
姓名:<inputtype="text"name="username">
密码:<inputtype="password"name="password"><inputtype="submit"value="提交"></form></body></html>
启动Tomcat测试
启动成功,访问:http://localhost:8080/list.jsp
填入数据,点击提交。
提交成功,查看数据库写入
SSM环境整合成功!!!
SSM矿建demo工程已上传至github:https://github.com/Bryant6/SSM_Demo.git
SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html
版权归原作者 1 + 1=王 所有, 如有侵权,请联系我们删除。