SSM整合(spring-springmvc-mybatis)之HelloWorld
Posted 啄木鸟伍迪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM整合(spring-springmvc-mybatis)之HelloWorld相关的知识,希望对你有一定的参考价值。
一、目录结构
helloworld(SSM)创建步骤:
步骤一:创建一个类型为Dynamic Web Project 名称为ssm的项目
步骤二:加入jar包:
spring核心jar包:
- commons-logging-1.2.jar
- spring-beans-5.3.10.jar
- spring-context-5.3.10.jar
- spring-core-5.3.10.jar
- spring-expression-5.3.10.jar
spring aop:
- spring-aop-5.3.10.jar
- spring-aspects-5.3.10.jar
springmvc jar包:
- spring-web-5.3.10.jar
- spring-webmvc-5.3.10.jar
spring 数据库交互jar包:
- spring-jdbc-5.3.10.jar
- spring-tx-5.3.10.jar
mybatis jar包:
- mybatis-3.5.9.jar
- mysql-connector-java-8.0.27 (1).jar
- log4j-1.2.17.jar
mybatis-spring 适配器包:
- mybatis-spring-1.3.2.jar
c3po:
- c3p0-0.9.5.5.jar
- c3p0-oracle-thin-extras-0.9.5.5.jar
- mchange-commons-java-0.2.19.jar
MyBatis-Spring下载地址:
https://github.com/mybatis/spring 在release中选择对应的版本下载即可;
步骤三:配置
web.xml:
- 配置DispacherServlet
- 配置启动spring ioc容器的Listener
配置说明,可参考十二、springMVC整合spring
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置DispatcherServlet(快捷键 alt +/) --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置DispatcherServletd 一个初始化参数:配置springmvc配置文件的位置和名称 --> <!-- 实际上也可以不通过 contextConfigLocation 来配置Springmvc的配置文件,而是用默认的 即默认的配置文件为 /WEB-INF/<servlet-name>-servlet.xml 本项目默认位置配置文件即为: /WEB-INF/springDispatcherServlet-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 表示springDispatcherServlet在加载的时候被创建 --> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc.xml:
基础配置(扫描包配置+视图解析器配置+<mvc:annotation-driven></mvc:annotation-driven>)
配置说明,可参考十二、springMVC整合spring spring和springmvc 整合时对扫描包做了特殊处理,来解决重复扫描包启动时实例化两次的问题;
<?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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- spirngmvc 只负责 网站跳转逻辑 --> <context:component-scan base-package="ssm" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven></mvc:annotation-driven> </beans>
spring.xml:
扫描包配置+数据源配置+事务配置+mybatis配置;
扫描包配置:请参考十二、springMVC整合spring spring和springmvc 整合时对扫描包做了特殊处理,来解决重复扫描包启动时实例化两次的问题;
数据源配置:和四、JdbcTemplate的配置 中的配置是一样的;
mybatis配置:
- 创建出 sqlSessionFactoryBean对象
- 配置一个可以进行批量执行的sqlSession
- 扫描所有的mapper接口的实现,让这些mapper能够自动注入
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- spring 希望管理所有的业务逻辑组件,等 --> <!-- 自动扫描配置 --> <context:component-scan base-package="ssm" use-default-filters="false"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <!-- spring用来控制业务逻辑。数据源、事务控制、aop... --> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:dbconfig.properties" /> <!-- 配置c3p0数据源 --> <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="$jdbc.username"></property> <property name="password" value="$jdbc.password"></property> <property name="driverClass" value="$jdbc.driver"></property> <property name="jdbcUrl" value="$jdbc.url"></property> </bean> <!-- spring 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"></property> </bean> <!-- 开启基于注解的事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 整合mybatis目的: 1.spring管理所有组件。mapper的实现类。可以对service中引用dao的内容,可以为@Autowired 自动注入mapper; 2.spring用来管理声明式事务, --> <!-- 创建出 sqlSessionFactoryBean对象 --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"></property> <!-- configLocation指定全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 指定mapper位置(如果mapper与mapper接口的文件名不一样的话这里需要配置,若一样就可以不配置) --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!--配置一个可以进行批量执行的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!-- 扫描所有的mapper接口的实现,让这些mapper能够自动注入 --> <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 配置SqlSessionFactoryBean的名称 <property name="basePackage" value="ssm.mapper" /> </bean> --> <mybatis-spring:scan base-package="ssm.mapper" /> </beans>
dbconfig.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis jdbc.username=root jdbc.password= jdbc2.driver=com.mysql.jdbc.Driver jdbc2.url=jdbc:mysql://localhost:3306/mybatis2 jdbc2.username=root jdbc2.password=
mybatis-config.xml:
具体的mybatis的全局配置文件说明请参看二、mybatis全局配置文件说明
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- settings包含很多重要的设置项; name:设置项的名字,value设置项的取值 --> <settings> <!-- 开启驼峰命名 比如数据库字段为Last_Name 则 自动变为lastName --> <setting name="mapUnderscoreToCamelCase" value="true" /> <!-- 分步查询配合一下两个配置 实现懒加载(按需加载) --> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="false" /> </settings> <!-- 配置顺序,properties settings typeAliases typeHandlers objectFactory objectWrapperFactory reflectFactory plugings environment databaseIdProvider mappers --> </configuration>
log4j.properties:
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %dyyyy-MM-dd HH:mm:ss,SSS method:%l%n%m%n ### 输出DEBUG 级别以上的日志到=E://logs/error.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-dyyyy-MM-dd HH:mm:ss [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =E://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-dyyyy-MM-dd HH:mm:ss [ %t:%r ] - [ %p ] %m%n ### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %dyyyy-MM-dd HH:mm:ss,SSS method:%l%n%m%n ### 输出DEBUG 级别以上的日志到=E://logs/error.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-dyyyy-MM-dd HH:mm:ss [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =E://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-dyyyy-MM-dd HH:mm:ss [ %t:%r ] - [ %p ] %m%n
代码部分:
EmployeeController.java:
package ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import ssm.entity.Employee; import ssm.service.EmployeeService; @RequestMapping("/emp") @Controller public class EmployeeController @Autowired private EmployeeService employeeService; @RequestMapping("/getEmp") public ModelAndView getById(Employee employee) ModelAndView mv = new ModelAndView("success"); mv.addObject("employee", employeeService.getEmpById(employee.getId())); return mv;
Employee.java
package ssm.entity; public class Employee 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 + "]";
EmployeeService.java
package ssm.service; import ssm.entity.Employee; public interface EmployeeService Employee getEmpById(Integer id);
EmployeeServiceImpl.java
package ssm.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ssm.entity.Employee; import ssm.mapper.EmployeeMapper; @Service("employeeService") public class EmployeeServiceImpl implements EmployeeService @Autowired private EmployeeMapper employeeMapper; @Override public Employee getEmpById(Integer id) return employeeMapper.getEmpById(id);
EmployeeMapper.java
package ssm.mapper; import ssm.entity.Employee; public interface EmployeeMapper Employee getEmpById(Integer id);
EmployeeMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="ssm.mapper.EmployeeMapper"> <select id="getEmpById" resultType="ssm.entity.Employee"> select * from tbl_employee where id=#id,jdbcType=INTEGER </select> </mapper>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h3>success</h3> <p>$employee.id</p> </body> </html>
运行结果:
当运行http://localhost:8080/SSM/emp/getById?id=1 时,跳转到了success页面,且形式了当前的id;
我从来不相信什么懒洋洋的自由。我向往的自由是通过勤奋和努力实现的更广阔的人生。
我要做一个自由又自律的人,靠势必实现的决心认真地活着。
以上是关于SSM整合(spring-springmvc-mybatis)之HelloWorld的主要内容,如果未能解决你的问题,请参考以下文章