SSM搭建详解
第一步骤:保证spring的Ioc独立运行
导入依赖
<!--spring和springmvc坐标--> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--spring整合mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!--导入德鲁伊数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!--导入junit测试坐标--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--spring整合junit--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!--jsp--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <!--解析切入点表达式的坐标--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <!--事务的坐标--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.4.RELEASE</version> </dependency> </dependencies>
编写业务层代码
public interface CompanyService { //查询所有 List<Company> findAll(); //根据id查询 Company findById(String id); //更新 void update(Company company); }
ServiceImpl实现类
@Service public class CompanyServiceImpl implements CompanyService { private CompanyDao companyDao; public List<Company> findAll() { System.out.println("执行了查询所有的方法"); return null; } public Company findById(String id) { return null; } public void update(Company company) { } }
spring配置文件
<?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" xsi:schemaLocation="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"> <!--配置spring容器要扫描的包--> <context:component-scan base-package="包名....."> <!--排除Controller注解--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> </beans>
测试保证spring的IOC独立运行
public class Test01SpringIoc { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); CompanyService serviceImpl = applicationContext.getBean("companyServiceImpl",CompanyService.class); System.out.println(serviceImpl.findAll()); } }
结果
[外链图片转存失败(img-vub6kYlh-1569163462217)(D:\Zone\CSDN\TimeFriends\九月\9月8日\springIOC.png)]
第二步保证Mybatis独立运行
创建mybatis的配置文件
SqlMapConfig.xml
<?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> <!--引入properties文件--> <properties resource="jdbc.properties"> </properties> <!--配置环境--> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </dataSource> </environment> </environments> <!--指定映射文件的位置--> <mappers> <package name="com.itheima.dao"></package> </mappers> </configuration>
jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/company_e88 jdbc.username=root jdbc.password=root
CompanyDao.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"> <!--命名空间操作的是哪个dao--> <mapper namespace="com.itheima.dao.CompanyDao"> <!--配置数据库列名和实体类名称的对应关系--> <resultMap id="companyMap" type="com.itheima.dao.CompanyDao"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="expiration_date" property="expirationDate"></result> <result column="address" property="address"></result> <result column="license_id" property="licenseId"></result> <result column="representative" property="representative"></result> <result column="phone" property="phone"></result> <result column="company_size" property="companySize"></result> <result column="industry" property="industry"></result> <result column="remarks" property="remarks"></result> <result column="state" property="state"></result> <result column="balance" property="balance"></result> <result column="city" property="city"></result> </resultMap> <!--配置查询所有--> <select id="findAll" resultMap="companyMap"> select * from ss_company; </select> <!--配置根据id查询--> <select id="findById" resultMap="companyMap" parameterType="java.lang.String" > select * FROM ss_company where id=#{id} </select> <!--配置更新--> <update id="update" parameterType="com.itheima.domain.Company"> update ss_company set `name`=#{name}, expiration_date=#{expirationDate}, address=#{address}, license_id=#{licenseId}, representative=#{representative}, phone=#{phone}, company_size=#{companySize}, industry=#{industry}, remarks=#{remarks}, state=#{state}, balance=#{balance}, city=#{city} WHERE id=#{id} </update> </mapper>
编写测试类:
public class Test02Mybatis { public static void main(String[] args) throws IOException { //1.读取主配置文件 InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3.构建sqlSessionFactory SqlSessionFactory factory = builder.build(stream); //4.创建sqlSession SqlSession sqlSession = factory.openSession(); //5.创建dao接口的代理实现类 CompanyDao proxyMapper = sqlSession.getMapper(CompanyDao.class); //6.执行dao的方法 Company company = proxyMapper.findById("2"); System.out.println(company); //7.释放资源 sqlSession.close(); stream.close(); } }
第三步整合spring和mybatis
思路:spring接管SqlSessionFactory的创建,以及dao接口的代理实现类的创建
<?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" xsi:schemaLocation="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"> <!--配置spring容器要扫描的包--> <context:component-scan base-package="com.itheima"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> <!-----------------------------------------------------------------------------> <!--整合spring和mybatis--> <!--指定properties文件的位置--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据源操作数据库--> <property name="dataSource" ref="dataSource"> </property> </bean> <!--配置数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--自动创建dao接口的代理实现类并且存入Ioc容器--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itheima.dao"></property> </bean> </beans>
第四步保证spring事务的正常使用
<?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" xsi:schemaLocation="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"> <!--配置spring容器要扫描的包--> <context:component-scan base-package="com.itheima"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> <!-----------------------------------------------------------------------------> <!--整合spring和mybatis--> <!--指定properties文件的位置--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据源操作数据库--> <property name="dataSource" ref="dataSource"> </property> </bean> <!--配置数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--自动创建dao接口的代理实现类并且存入Ioc容器--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itheima.dao"></property> </bean> <!-----------------------------------------------------------------------------> <!--配置事务--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事务的通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--配置事务的属性--> <tx:attributes> <tx:method name="*" read-only="false" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="SUPPORTS"></tx:method> </tx:attributes> </tx:advice> <!--配置aop--> <aop:config> <!--配置切入点:.*.*(..) 任意类下的任意方法的有无返回值都可--> <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut> <!--建立切入点表达式和事务通知的关系--> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config> </beans>
在service实现类中加入注解@Autowried注入dao
@Autowired private CompanyDao companyDao; • 1 • 2
/** * 测试spring和mybatis的整合结果 */ /*创建容器*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class Test03SpringMybatis { @Autowired private CompanyService companyService; @Test public void testFindAll(){ List<Company> companyList = companyService.findAll(); for (Company company : companyList) { System.out.println(company); } } @Test public void testUpdate(){ Company company = companyService.findById("2"); company.setExpirationDate(new Date()); companyService.update(company); } }
第五步保证springMvc的独立运行
web.xml
<?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"> <!--配置前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置servlet的初始化参数,指定springmvc配置文件的位置--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!--配置servlet启动时候就创建--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!--*.do与/的区别:/访问静态资源的时候需要配置mvc:resources--> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--配置字符集过滤器,过滤器的生命周期是项目启动--> <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> </web-app>
springmvc.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置springmvc创建容器时扫描的包--> <context:component-scan base-package="com.itheima.controller"></context:component-scan> <!--配置视图解析器--> <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--开启springmvc的注解支持--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
Controller层
@Controller @RequestMapping("/company") public class CompanyController { //没有注入是因为这一步骤是保证springmvc的独立运行 private CompanyService companyService; /** * 配置查询所有 * @return */ @RequestMapping("/list") public String findAll(){ System.out.println("执行了查询所有"); return ""; } }
在web.xml中配置监听器(监听项目启动的时候就创建容器解决注入不进去的问题)
CompanyController类
注意:update需要重定向,如果请求转发那么地址栏不会发生变化,刷新会导致再次更新.所以update需要重定向.
@Controller @RequestMapping("/company") public class CompanyController { @Autowired private CompanyService companyService; /** * 配置查询所有 * @return */ @RequestMapping("/list") public String findAll(HttpServletRequest request){ List<Company> companyList = companyService.findAll(); //存到请求域中 request.setAttribute("list",companyList); //转发到列表页面 return "company-list"; } /** * 前往更新页面,根据id查询 * @return */ @RequestMapping("/toUpdate") public String toUpdate(String id,HttpServletRequest request){ Company company = companyService.findById(id); //存入到请求域中 request.setAttribute("company",company); companyService.update(company); return "company-update"; } @RequestMapping("/edit") public String edit(Company company){ companyService.update(company); //重定向到列表页面 return "redirect:/company/list.do"; } }
}
/** * 前往更新页面,根据id查询 * @return */ @RequestMapping("/toUpdate") public String toUpdate(String id,HttpServletRequest request){ Company company = companyService.findById(id); //存入到请求域中 request.setAttribute("company",company); companyService.update(company); return "company-update"; } @RequestMapping("/edit") public String edit(Company company){ companyService.update(company); //重定向到列表页面 return "redirect:/company/list.do"; }
}