Spring MVC之SSM框架整合

tech2022-08-16  143

Spring MVC之SSM框架整合

一、添加依赖三、添加Spring框架1.配置spring.xml2.注解配置Service层、Dao层3.配置日志4.执行测试 四、添加Spring MVC框架1.配置springmvc.xml2.配置web.xml3.注解配置Controller表现层 五、整合 Spring和SpringMVC六、添加Mybatis框架1.编写注解SQL2.配置 SqlMapConfig.xml3.执行测试 七、整合Spring和MyBatis八、配置 spring 的事务九、测试整合结果1.执行方法测试2.Controller表现层添加方法3.编写Jsp页面

一、添加依赖

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.2.8.RELEASE</spring.version> <spring.aspectj>1.9.6</spring.aspectj> <slf4j.version>1.7.30</slf4j.version> <log4j.version>1.2.17</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.5.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${spring.aspectj}</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.13</version> <scope>compile</scope> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--Servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!--jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!--el表达式--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志相关 --> <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> <!-- 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.3.3</version> </dependency> <!--c3po连接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>

三、添加Spring框架

1.配置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和dao,controller不需要Spring框架扫描处理--> <context:component-scan base-package="cn.ybzy" > <!--配置那种类型注解不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> </beans>

2.注解配置Service层、Dao层

Account 实体类 public class Account implements Serializable{ private Integer id; private String name; private Double money; //getter() setter() } AccountDao接口与AccountDaoImpl实现类 public interface AccountDao { void save(Account account); List<Account> findAll(); } @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Override public List<Account> findAllAccount() { System.out.println("Dao查询所有账户..."); return null; } @Override public void saveAccount(Account account) { System.out.println("Dao保存账户..."); } } AccountService接口与AccountServiceImpl实现类 public interface AccountService { // 查询所有账户 public List<Account> findAll(); // 保存帐户信息 public void saveAccount(Account account); } @Service("accountService") public class AccountServiceImpl implements AccountService{ @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("Service查询所有账户..."); return accountDao.findAll(); } @Override public void saveAccount(Account account) { System.out.println("Service保存帐户..."); accountDao.saveAccount(account); } }

3.配置日志

log4j.rootCategory=info, CONSOLE, LOGFILE log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\spring-mvc.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

4.执行测试

@Test public void run1(){ // 加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml"); // 获取对象 AccountService as = (AccountService) ac.getBean("accountService"); // 调用方法 as.findAll(); }

四、添加Spring MVC框架

1.配置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="cn.ybzy"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--配置的视图解析器对象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--过滤静态资源--> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <!--开启SpringMVC注解的支持--> <mvc:annotation-driven/> </beans>

2.配置web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!--配置前端控制器--> <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> <!--启动服务器,创建该servlet--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</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>

3.注解配置Controller表现层

AccountController @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("Controller查询所有账户..."); // 调用service的方法 List<Account> list = accountService.findAll(); //使用model视图返回 model.addAttribute("list",list); return "list"; } }

五、整合 Spring和SpringMVC

在web.xml中配置spring的监听器实现启动服务创建容器 <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件--> <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>

六、添加Mybatis框架

1.编写注解SQL

@Repository public interface AccountDao { // 查询所有账户 @Select("select * from account") public List<Account> findAll(); // 保存帐户信息 @Insert("insert into account (name,money) values (#{name},#{money})") public void saveAccount(Account account); }

2.配置 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="jdbcConfig.properties"></properties>--> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="pooled"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--mapper映射器,扫描接口类--> <mapper class="cn.ybzy.dao.AccountDao"/> </mappers> </configuration>

3.执行测试

public class TestMyBatis { @Test public void test1() throws Exception { // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); // 获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); // 查询所有数据 List<Account> list = dao.findAll(); for(Account account : list){ System.out.println(account); } // 关闭资源 session.close(); in.close(); } @Test public void test2() throws Exception { Account account = new Account(); account.setName("大白"); account.setMoney(123D); // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); // 获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); // 保存 dao.saveAccount(account); // 提交事务 session.commit(); // 关闭资源 session.close(); in.close(); } }

七、整合Spring和MyBatis

整合Spring和MyBatis只需要把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中。 <!--Spring整合MyBatis框架--> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbcConfig.properties" />--> <!--配置连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssm"/> <property name="user" value="root"/> <property name="password" value="123456"/> </bean> <!--配置 MyBatis 的SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置扫描dao的包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.ybzy.dao"/> </bean>

八、配置 spring 的事务

<!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" read-only="false"/> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!--配置AOP--> <aop:config> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* cn.ybzy.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>

九、测试整合结果

1.执行方法测试

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:spring.xml"}) public class TestSpringMabatis { @Autowired private AccountService accountService; @Test public void testFindAll() { List list = accountService.findAllAccount(); System.out.println(list); } @Test public void testSave() { Account account = new Account(); account.setName("Test"); account.setMoney(123D); accountService.saveAccount(account); } }

2.Controller表现层添加方法

@RequestMapping("/findAll") public ModelAndView findAll() { List<Account> accounts = accountService.findAll(); ModelAndView mv = new ModelAndView(); mv.addObject("accounts", accounts); mv.setViewName("accountlist"); return mv; } @RequestMapping("/saveAccount") public String saveAccount(Account account) { accountService.saveAccount(account); return "redirect:findAll"; }

3.编写Jsp页面

index.jsp :保存页面 <body> <a href="account/findAll">查询所有账户</a> <hr/> <form action="account/saveAccount" method="post"> 账户名称:<input type="text" name="name"/><br/> 账户金额:<input type="text" name="money"><br/> <input type="submit" value=" 保存 "/> </form> </body> 账户列表页面: accountlist.jsp <body> <table border="1" width="300px"> <tr> <th>编号ID</th> <th>账户名称</th> <th>账户金额</th> </tr> <c:forEach items="${accounts}" var="account" varStatus="as"> <tr> <!--varStatus as.count输出行号,从1开始--> <td>${as.count}</td> <td>${account.name }</td> <td>${account.money }</td> </tr> </c:forEach> </table> </body>
最新回复(0)