springMVC框架学习安排
目录
第三天
SSM整合案例
整合步骤: &&表示整合
- spring
- springMVC
- spring&&springMVC
- mybatis
- spring&&mybatis
- SSM
1.spring框架搭建
-
创建maven工程,选择骨架创建
结束后为项目添加所需的目录 -
项目目录结构
-
添加所必须的代码
- 引入pom.xml坐标
<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.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> <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>compile</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>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>
- dao
@Repository("accountDao") public interface AccountDao { //查询所有用户 public List<Account> findAll(); //保存 public void saveAccount(Account account); }
- service
public interface AccountService { //查询所有用户 public List<Account> findAll(); //保存 public void saveAccount(Account account); }
@Service("accountService") public class AccountServiceImpl implements AccountService{ @Override public List<Account> findAll() { System.out.println("业务层:findAll"); return null; } @Override public void saveAccount(Account account) { System.out.println("业务层:saveAccount"); } }
- controller
@Controller @RequestMapping("/account") public class AccountController { }
- 实体类
public class Account implements Serializable { private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer 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 + '}'; } }
- spring配置文件applicationContext.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"> <!--配置创建IOC容器要扫描的包--> <context:component-scan base-package="com.liuzeyu"> <!--不扫描配置注解Controller的类--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
简单测试环境是否可以运行spring项目:
public class SSMTest { @Test public void test01(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = (AccountService) ac.getBean("accountService"); accountService.findAll(); } }
测试结果:
OK,spring项目搭建成功!
2.springMVC框架搭建
- 新建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/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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置扫描controller-->
<context:component-scan base-package="com.liuzeyu">
<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 mapping="/js/**" location="/js/"/>
<!--开启springMVC注解支持-->
<mvc:annotation-driven/>
</beans>
- web.xml的编写
<!DOCTYPE web-app PUBLIC
"-//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>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置初始化参数,当DispatcherServlet创建完之后加载springmvc.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--服务器启动时创建DispatcherServlet-->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- controller的编写
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("findAll")
public String findAll(){
System.out.println("查询所有被执行了");
return "list";
}
}
- jsp的测试界面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/account/findAll">查询所有</a>
</body>
</html>
list.jsp
测试结果:
OK,springMVC环境也配置成功!
3.spring整合springMVC框架搭建
完成springMVC的环境搭建,我们发现一个问题,当服务器启动后,controller层无法去调用service的对象,注入无法成功,为什么呢?
@Autowired
private AccountService accountService;
因为spring的配置文件没有在服务器启动后被加载,查看web.xml文件:
它只会去加载springMVC的文件,把controller加入IOC容器中,dao和service并没有被加入IOC容器中。由此可见,我们想要整合springMVC就必须将spring的配置文件也要加载搭配spring的容器中
<mark>方案思路:</mark>
所以我们需要去监听servletContext的创建时机,如何监听?借助spring为我们提供的***,一旦servletContext创建成功,就可以加载spring文件
web.xml
的配置:
<!--配置***,监听servletContext的创建-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--执行servletContext创建后要加载的文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
测试结果:业务层被controller成功调用
4.MyBatis框架环境搭建
- 配置dao到的接口方法,使用注解的方式插入sql语句
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);
}
- mybatis的主配置文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--数据库主配置环境-->
<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="809080"/>
</dataSource>
</environment>
</environments>
<!--接口的映射配置-->
<mappers>
<!--<mapper class="com.liuzeyu.dao.AccountDao"/>-->
<!--加载dao下的所有接口-->
<package name="com.liuzeyu.dao"/>
</mappers>
</configuration>
- 测试方法
public class MyBatisTest {
/** * 查询方法 * @throws IOException */
@Test
public void test01() throws IOException {
//加载MyBatis主配置文件
InputStream is = Resources.getResourceAsStream("SqlMapperConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象,查询方法无需事务的支持
SqlSession sqlSession = factory.openSession();
//创建dao的代理对象
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
//执行方法
List<Account> list = accountDao.findAll();
//遍历
for (Account account : list) {
System.out.println(account);
}
//是否资源
sqlSession.close();
is.close();
}
/** * 查询方法 * @throws IOException */
@Test
public void test02() throws IOException {
//加载MyBatis主配置文件
InputStream is = Resources.getResourceAsStream("SqlMapperConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象,并开启事务的自动提交
SqlSession sqlSession = factory.openSession(true);
//创建dao的代理对象
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
//执行方法
Account account = new Account();
account.setName("laowang");
account.setMoney(5000.0);
accountDao.saveAccount(account);
//是否资源
sqlSession.close();
is.close();
}
}
- 测试结果
保存方法:
查询方法:
4.spring整合MyBatis框架
同样遇到问题:我们service如何得到dao的接口对象呢?
<mark>分析:</mark>
当服务器启动后,tomcat服务器加载springMVC配置文件,***加载spring配置文件,虽然可以将dao的接口对象加入到IOC容器中,但是由于没有实现类,故我们在myabatis中是使用的代理dao的方式执行dao层的方法。
<mark>解决方案:</mark>
出发点如何将代理dao加入到IOC容器中?
步骤:在spring的配置文件中
-
配置连接池
-
配置SqlSessionFactory
-
配置创建AccountDao所在的包
这样就可以创建出代理的dao对象并存入容器中。此时mybatis的主配置文件就可以删除掉了
因为我们已经将mybatis的环境整合到了spring中。 -
为AccountDao加上注解
@Repository("accountDao")
-
service层实现类调用dao层方法
@Service("accountService") public class AccountServiceImpl implements AccountService{ @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("业务层:findAll"); return accountDao.findAll(); } @Override public void saveAccount(Account account) { accountDao.saveAccount(account); System.out.println("业务层:saveAccount"); } }
-
controller调用service方法并且返回前端
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("findAll") public String findAll(Model model){ List<Account> list = accountService.findAll(); model.addAttribute("list",list); System.out.println("查询所有被执行了"); return "list"; } }
-
前端解析遍历结果
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h2>查询到所有</h2> <c:forEach items="${list}" var="account"> ${ account.name} </c:forEach> </body> </html>
-
测试结果
5.添加spring的事务控制器
- 配置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="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.liuzeyu.service.impl.*.*(..))"/>
</aop:config>
- 为controller添加保存方法
@RequestMapping("save")
public void save(Account account, HttpServletRequest request,
HttpServletResponse response) throws IOException {
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
System.out.println("保存被执行了---AccountController");
return;
}
测试结果: