1.创建数据库和表结构
create database ssm;
create table account(
id int primary key auto_increment,
name varchar(100),
money double(7,2)
)
2.创建Maven工程
3.导入坐标并配置依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itcast</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<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>
<shiro.version>1.2.3</shiro.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<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>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
4.编写实体类
在source root下创建cn.itcast.domain创建实体类:
package cn.itcast.domain;
import java.io.Serializable;
/**
-
账户信息
*/
public class Accout 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;
}
}
5.编写持久层接口
在source root下创建cn.itcast.dao编写业务层接口:
package cn.itcast.dao;
import cn.itcast.domain.Accout;
import java.util.List;
/**
* 账户接口
*/
public interface AccoutDao {
//查询所有账户信息
public List<Accout> findAll();
//保存账户信息
public void saveAccout(Accout accout);
}
6. 业务层接口及业务层接口实现类
在source root下创建cn.itcast.service编写业务层接口:
package cn.itcast.service;
import cn.itcast.domain.Accout;
import java.util.List;
public interface AccountService {
//查询所有账户信息
public List<Accout> findAll();
//保存账户信息
public void saveAccout(Accout accout);
}
在source root下创建cn.itcast.service.impl编写业务层接口实现类:
package cn.itcast.service.impl;
import cn.itcast.domain.Accout;
import cn.itcast.service.AccountService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
public List<Accout> findAll() {
System.out.println("业务层:查询所有账户。。。");
return null;
}
public void saveAccout(Accout accout) {
System.out.println("业务层:保存账户。。。");
}
}
此时,整合环境已经搭建完成。接下来进行spring的配置。
7. 配置spring
在resources root(resource)下创建applicationContext.xml文件,填写具体的配置信息,并开启注解的扫描,希望处理source root下的service和dao中的注解,controller不需要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"
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.itcast">
<!--配置哪些注解不扫描,annotation表示注解,-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
8.对spring进行测试
在source root下创建cn.itcast.root,创建测试类TestSpring:
package cn.itcast.test;
import cn.itcast.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void run1(){
// 加载配置文件,即resources中的applicationContext.xml文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象,即java.cn.itcast.service.impl.AccountServiceImpl中的注解
AccountService as = (AccountService) ac.getBean("accountService");
// 调用其中的findAll()方法
as.findAll();
}
}
右键run1,得到[ main] INFO ry.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml] 业务层:查询所有账户。。
在之前,需要在resources中添加log4j.properties配置文件。
到此,spring的开发环境搭建完成,接下来搭建springmvc框架环境。
9. 搭建springmvc框架
1. 设计请求页面
在webapp中删除并新建index.jsp:
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2021/3/6
Time: 10:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--account表示类的注解,findAll表示方法的注解--%>
<a href="account/findAll">测试</a>
</body>
</html>
2.在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>
<!--配置前端控制器,设计名为dispatcherServlet的servlet前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件,即resources中的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-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决中文乱码的过滤器,设计名为characterEncodingFilter的filter过滤器-->
<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-->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!--拦截内容,/*表示什么都拦截-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
由于其中
<!--加载springmvc.xml配置文件,即resources中的springmvc.xml。即设计控制范围-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
指定了配置文件为springmvc.xml,所以设计springmvc配置文件。
3.设计springmvc配置文件
在resource root中创建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注解,即java下的cn.itcast.controller包-->
<context:component-scan base-package="cn.itcast">
<!--org.springframework.stereotype.Controller对应@Controller层-->
<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>
由于在springmvc.xml中设计了
<!--org.springframework.stereotype.Controller对应@Controller层-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
表示只扫描Controller下的注解,而controller注解出现在source root下的cn.itcast.controller.AccountController文件中,所以要在该文件下添加account/findAll的注解,用于响应页面请求:
4.设计AccountController文件
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 账户web
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有的账户信息。。。");
//注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
return "list";
}
}
此时,当请求页面发送请求时,会调用该页面下的findAll()方法,该方法运行后会返回list,而list会在视图管理器管理的页面中会有一个对应的list.jsp文件,作为返回界面,因此需要设计list.jsp文件:
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2021/3/6
Time: 10:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询了所有的账户信息</h3>
</body>
</html>
4.配置Tomcat
运行Tomcat,发送请求即可。
10.创建spring整合springmvc的框架
想要spring整合springmvc,即当运行tomcat时springmvc能够调用spring中的方法即可。
由于启动Tomcat->创建Servlet->加载springmvc.xml->只扫描*@Controller注解,从头到尾都没有加载source root中的cn.itcast.service.impl中的@Service注解,所以我们需要使用监听器,监听器也是在Tomcat服务器运行的时候启动的,即启动Tomcat->创建监听器Listener->加载applicationContext.xml->扫描@Service*注解。如此一来,便将spring和springmvc中的注解同时扫描了,之后就在控制器中调用即可。
1.在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>
<!--配置spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml(该文件在resource root目录下)-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置前端控制器,设计名为dispatcherServlet的servlet前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件,即resources中的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-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决中文乱码的过滤器,设计名为characterEncodingFilter的filter过滤器-->
<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-->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!--拦截内容,/*表示什么都拦截-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
注意,监听器要配置监听文件的位置:
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2.在AccountController注入service对象,调用service对象方法
package cn.itcast.controller;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 账户web
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired//按类型注入
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有的账户信息。。。");
//调用service的方法(业务层)
accountService.findAll();
//注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
return "list";
}
}
测试即可,print:
表现层,查询所有的账户信息。。。
业务层:查询所有账户。。。
11. spring整合Mybatis框架
写到这发现前面的account拼错了,现在全部改正。
运行时报了以下错误,我心一凉,以为不能改,后来发现是配置mybatis时字母打错了,所以遇事不要慌,仔细检查一遍,确认没问题/不会后->百度。参考链接如下:NullPointerException
org.apache.ibatis.exceptions.PersistenceException: ### Error opening session. Cause: java.lang.NullPointerException ### Cause: java.lang.NullPointerException
11.1搭建MyBatis框架
11.1.1在source root下的cn.itcast.dao.AccountDao接口添加注解,并填写sql语句
package cn.itcast.dao;
import cn.itcast.domain.Account;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 账户接口
*/
public interface AccountDao {
//查询所有账户信息
@Select("select * from account")
public List<Account> findAll();
//保存账户信息,#{name}表示从accout取值
@Insert("insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
}
11.1.2. 在resource root下创建连接数据库的配置文件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>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
<!--具体:<mapper class="cn.itcast.dao.AccountDao"/>-->
<package name="cn.itcast.dao"/>
</mappers>
</configuration>
11.1.3. 在source root 下的cn.itcast.test编写MyBatis的测试文件TestMyBatis.java
package cn.itcast.test;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.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 run1() 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();
}
}
运行run1()函数,得到:
Account{id=1, name='xxx', money=111.0}
Account{id=2, name='aaa', money=222.0}
11.1.4. 在source root 下的cn.itcast.test.TestMyBatis.java编写测试MyBatis的Save方法
package cn.itcast.test;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
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 {
/**
* 测试查询
* @throws Exception
*/
@Test
public void run1() 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();
}
/**
* 测试保存
* @throws Exception
*/
@Test
public void run2() throws Exception {
Account account = new Account();
account.setName("大王");
account.setMoney(400d);
//加载配置文件
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();
}
}
运行run()2即可,刷新数据得到新的一行数据。