新建一个web工程
建立各自层面的包:持久层dao,业务层service,表现层controller,实体类domain包
新建各自的接口或者实现类
创建applicationContext.xml配置文件并复制头文件于内(头文件自己网上随便找)
开启spring扫描的包
applicationContext.xml
<context:component-scan base-package="com.itheima">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
在service包下的impl包实现类添加@service注解,加入容器
测试spring框架
@Test
public void testSpring(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService as = ac.getBean("accountService", AccountService.class);
as.findAllAccount();
}
配置web.xml文件
web.xml
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
web-app>
建立springmvc.xml文件并导入头约束文件(需要更多约束自己网上随便找得到)
springmvc.xml
<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">
<context:component-scan base-package="com.itheima">
<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/**" />
<mvc:annotation-driven/>
beans>
使用controller包下的控制类测试
HelloController.java
@Controller
@RequestMapping("/user")
public class HelloController {
@RequestMapping("/hello")
public String findAll() throws Exception{
return "index";
}
}
此处使用注解的方式,和代理Dao实现
AccountDao.java
public interface AccountDao {
@Select("select * from account")
List<Account> findAllAccount();
@Update("insert into account value(#{id},#{name},#{money})")
void saveAccount(Account account);
导入log4j.properties配置文件(网上自己找,很多)
新建SqlMapConfig.xml并写入头文件配置(网上百度mybatis配置文件头文件)
SqlMapConfig.xml
<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/eesy_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.itheima.dao"/>
mappers>
configuration>
@Test
public void mybatis() throws IOException {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
List<Account> allAccount = accountDao.findAllAccount();
for (Account account : allAccount) {
System.out.println(account);
}
sqlSession.close();
in.close();
}
版本锁定(pom.xml配置文件中)
<spring.version>5.0.2.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<mysql.version>5.1.6mysql.version>
<mybatis.version>3.4.5mybatis.version>
jar包(pom.xml配置文件中)
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.8version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>compilescope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
<type>jartype>
<scope>compilescope>
dependency>
dependencies>
目的:在controller中能成功的调用service对象中的方法。
在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(须在web.xml中添加如下配置)。
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
在controller中注入service对象,调用service对象的方法进行测试
在applicationContext.xml中添加配置连接池和代理Dao所需要的配置
applicationContext.xml
<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="root"/>
bean>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
bean>
配置到此处,可以删除原来的mybatis配置文件(SqlMapConfig.xml),spring成功整合mybatis
配置spring的持久层的声明式事务控制
applicationContext.xml
<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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))">aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
aop:config>
注意:在jsp文件添加如下引入代码:
<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
表示 jstl(jsp标准标记库)的语句,导入之后,你就可以使用jstl中的标签了.
最终的表现层代码
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<a href="account/findAllAccount">测试查询a><br>
<form action="account/saveAccount" method="post">
姓名:<input type="text" name="name"/><br>
余额:<input type="text" name="money"/><br>
<input type="submit" value="提交"/><br>
form>
body>
html>
list.jsp
<%@ 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>Titletitle>
head>
<body>
<c:forEach items="${list}" var="account">
${account.id}${account.name}${account.money}<br>
c:forEach>
<h3>执行成功h3>
body>
html>
AccountController.java
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAllAccount")
public String findAllAccount(Model model){
System.out.println("表现层:测试查询");
List<Account> accounts = accountService.findAllAccount();
model.addAttribute("list",accounts);
return "list";
}
@RequestMapping("/saveAccount")
public void saveAccount(Account account, HttpServletResponse response, HttpServletRequest request) throws IOException {
System.out.println("表现层:添加账户");
accountService.saveAccount(account);
//重定向到查询所有界面
response.sendRedirect(request.getContextPath()+"/account/findAllAccount");
return ;
}
}