这篇文章给大家介绍如何搭建一个SSM空间,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
整合的思路
2.1. 先搭建整合的环境
2.2. 先把Spring的配置搭建完成
2.3. 再使用Spring整合SpringMVC框架
2.4. 最后使用Spring整合MyBatis框架
创建数据库和表结构
3.1创建数据库
create database ssm; create table account( id int primary key auto_increment, name varchar(20), money double );
4.创建maven工程
<properties> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!--spring--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</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-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-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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--log start--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version></dependency> </dependencies> <build> <finalName>ssm</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </pluginManagement> </build>
编写实体类,在ssm_domain项目中编写
package com.qcby.entity; import java.io.Serializable; public class Account implements Serializable { // 主键 private int id; // 账户名称 private String name; // 账号的金额 private Double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
编写service接口和实现类
package com.qcby.service; import com.qcby.entity.Account; import java.util.List; public interface AccountService { //查询所有 public List<Account> findAll(); }
package com.qcby.service; import com.qcby.entity.Account; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { //查询所有 @Override public List<Account> findAll() { System.out.println("业务层:查询所有"); return null; } }
1. 搭建和测试Spring的开发环境
在ssm_web项目中创建spring.xml的配置文件,编写具体的配置信息。
<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!--开启注解扫描,要扫描的是service--> <context:component-scan base-package="com.qcby.service"/> </beans>
在ssm_web项目中编写测试方法,进行测试
package com.qcby.demo; import com.qcby.service.AccountService; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring { @Test public void run(){ ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml"); AccountService service = ac.getBean(AccountService.class); service.findAll(); } }
在web.xml中配置DispatcherServlet前端控制器
<!--配置前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载springmvc.xml配置文件--> <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.xml中配置DispatcherServlet过滤器解决中文乱码
<!--解决post请求中文乱码的过滤器--> <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>
创建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:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> <!--扫描controller的注解,别的不扫描--> <context:component-scan base-package="com.qcby.controller"/> <!-- 配置视图解析器--> <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--JSP文件所在的目录--> <property name="prefix" value="/pages/"/> <!--文件的后缀名--> <property name="suffix" value=".jsp"/> </bean> <!--设置静态资源不过滤--> <mvc:resources mapping="/source/css/**" location="/source/css/"/> <mvc:resources mapping="/source/js/**" location="/source/js/"/> <mvc:resources mapping="/source/images/**" location="/source/images/"/> <!--开启springmvc--> <mvc:annotation-driven/> </beans>
测试SpringMVC的框架搭建是否成功
4.1. 编写index.jsp和list.jsp编写,超链接
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查询所有</a> </body> </html>
4.2. 创建AccountController类,编写方法,进行测试
package com.qcby.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/account") public class AccountController { /** * 查询所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有"); ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
目的:在controller中能成功的调用service对象中的方法。
在项目启动的时候,就去加载spring.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文
件,所以要配置全局的变量加载类路径下的配置文件)。
<!--配置Spring的监听器--> <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:spring.xml</param-value> </context-param>
在controller中注入service对象,调用service对象的方法进行测试
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; 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 java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依赖注入 @Autowired private AccountService accountService; /** * 查询所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有"); //调用service的方法 List<Account> list = accountService.findAll(); ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
在web项目中编写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 resource="jdbc.properties"></properties> <!--定义别名--> <typeAliases> <!--把com.qcby.entity.User使用user别名来显示,别名user User USER都可以,默认是忽略大写的--> <!--<typeAlias type="com.qcby.entity.User" alias="user"/>--> <!--针对com.qcby.entity包下的所有的类,都可以使用当前的类名做为别名--> <package name="com.qcby.entity"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <!--配置事务的类型,使用本地事务策略--> <transactionManager type="JDBC"></transactionManager> <!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/AccountDao.xml"></mapper> </mappers> </configuration>
AccountDao接口
package com.qcby.dao; import com.qcby.entity.Account; import java.util.List; public interface AccountDao { //查询所有 public List<Account> findAll(); }
编写AccountDao.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="com.qcby.dao.AccountDao"> <select id="findAll" resultType="account"> select * from account </select> </mapper>
编写测试的方法
package com.qcby.demo; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestMybatis { @Test public void run() throws IOException { InputStream in = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); SqlSession session = factory.openSession(); AccountDao mapper = session.getMapper(AccountDao.class); List<Account> list = mapper.findAll(); for (Account account : list) { System.out.println(account); } //关闭资源 session.close(); in.close(); } }
目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
在service中注入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" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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:property-placeholder location="classpath:jdbc.properties"/> <!--开启注解扫描,要扫描的是service--> <context:component-scan base-package="com.qcby.service"/> <!--配置数据库连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--Spring整合MyBatis框架,SqlSessionFactoryBean创建工厂对象--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.qcby.entity" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--配置扫描Dao接口包,动态实现Dao接口,注入到ioc容器中--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qcby.dao"/> </bean> </beans>
service代码如下
package com.qcby.service; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; //查询所有 @Override public List<Account> findAll() { System.out.println("业务层:查询所有"); List<Account> list = accountDao.findAll(); return list; } }
controller代码如下
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; 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 java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依赖注入 @Autowired private AccountService accountService; /** * 查询所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有"); //调用service的方法 List<Account> list = accountService.findAll(); for (Account account : list) { System.out.println(account); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
spring.xml配置声明式事务管理
<!-- 配置声明式事务管理--> <!--平台事务管理器--> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务的通知--> <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" /> </tx:attributes> </tx:advice> <!--配置事务的增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.*ServiceImpl.*(..))"/> </aop:config>
表单代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查询所有</a> <form action="/account/save" method="post"> 姓名:<input type="text" name="name" /><br/> 金额:<input type="text" name="money" /><br/> <input type="submit" value="保存" /> </form> </body> </html>
controller代码
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; 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 java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依赖注入 @Autowired private AccountService accountService; /** * 查询所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有"); //调用service的方法 List<Account> list = accountService.findAll(); for (Account account : list) { System.out.println(account); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } @RequestMapping("/save") public String save(Account account){ //Service的保存方法 accountService.save(account); return "suc"; } }
service接口和实现类代码
package com.qcby.service; import com.qcby.entity.Account; import java.util.List; public interface AccountService { //查询所有 public List<Account> findAll(); //保存 void save(Account account); }
package com.qcby.service; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; //查询所有 @Override public List<Account> findAll() { System.out.println("业务层:查询所有"); List<Account> list = accountDao.findAll(); return list; } @Override public void save(Account account) { accountDao.save(account); } }
dao代码
package com.qcby.dao; import com.qcby.entity.Account; import java.util.List; public interface AccountDao { //查询所有 public List<Account> findAll(); //保存 void save(Account account); }
dao.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="com.qcby.dao.AccountDao"> <select id="findAll" resultType="account"> select * from account </select> <insert id="save" parameterType="account"> insert into account (name,money) values(#{name},#{money}) </insert> </mapper>
关于如何搭建一个SSM空间就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。