创建工程
在pom.xml文件中导入坐标版本、依赖
<?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>org.example</groupId>
<artifactId>ssm_test_02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm_test_02 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>
<mysql.version>8.0.16</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>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-->
<!-- 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.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_test_02</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>
在domain下创建实体类Account方法,生成get、set和tostring方法
package com.xl.domain;
import java.io.Serializable;
public class Account implements Serializable {
//id
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 +
'}';
}
}
在resources下创建日志文件 log4j.properties
log4j.rootLogger=INFO, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p - %m%n
搭建和测试sprigMvc的开发环境
在web.xml中配置DispatcherServlet、配置中文乱码
<!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>
<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>/*
在resource下创建springmvc.xml的配置 开启对controller注解的扫描、配置试图解析器、设置静态资源不过滤、开启对springmvc注解的支持
<?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">
<!--开启注解扫描,springmvc只负责扫描controller注解-->
<context:component-scan base-package="com.xl">
<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="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!--开启spirngmvc注解的支持-->
<mvc:annotation-driven/>
</beans>
在contoller下创建AccountController.java ,编写增删查改方法
package com.xl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/accounts")
public class AccountContoller {
//查询所有账户
@RequestMapping("/findAll")
public String findAll(){
System.out.println("web层,查询所有账户");
return "allcounts";
}
//根据id查询账户
@RequestMapping("/findBuid")
public String findBuid(){
System.out.println("web层,根据id查询账户");
return "allcounts";
}
//增加账户
@RequestMapping("/insertAccount")
public String insertAccount(){
System.out.println("web层,增加账户");
return "allcounts";
}
//删除账户
@RequestMapping("/deleteAccount")
public String deleteAccount(){
System.out.println("web层,删除账户");
return "allcounts";
}
//修改账户
@RequestMapping("/updateAccount")
public String updateAccount(){
System.out.println("web层,修改账户");
return "allcounts";
}
}
编写inex.jsp页面,提交的链接对应AccountController的方法名称
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/11/13
Time: 21:11
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>
<a href="accounts/findAll">查询所有账户</a> <br>
<form action="accounts/findBuid">
要查询账户的id:<input type="text" name="id">
<input type="submit" value="提交">
</form><br>
<form action="accounts/insertAccount">
要添加账户的信息:
<input type="text" name="name"><br>
<input type="text" name="money"><br>
<input type="submit" value="提交">
</form><br>
<form action="accounts/deleteAccount">
要删除账户的id:<input type="text" name="id">
<input type="submit" value="提交">
</form><br>
<form action="accounts/updateAccount">
要修改的账户的信息为:
<input type="text" name="name"><br>
<input type="text" name="money"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
在pages下面创建成功跳转页面 allcount.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/11/13
Time: 21:09
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>
<h1>加载成功!!!</h1>
</body>
</html>
搭建spirng层并整合springmvc层
在serice包下创建IAccountService接口
package com.xl.service;
import com.xl.domain.Account;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.List;
public interface IAccountService {
//查询所有账户
List<Account> findAll();
//根据id查询账户
Account findById(Integer id);
//增加账户
void insertAccount(Account account);
//删除账户
void deleteAccount(Integer id);
//修改账户信息
void updateAccount(Account account);
}
在service包下创建包impl并创建实现类AccountServiceImpl.java
package com.xl.service.impl;
import com.xl.domain.Account;
import com.xl.service.IAccountService;
import java.util.List;
@Service
public class AccountServiceImp implements IAccountService {
@Override
public List<Account> findAll() {
System.out.println("service层,查询所有账户");
return null;
}
@Override
public Account findById(Integer id) {
System.out.println("service层,根据id查询账户");
return null;
}
@Override
public void insertAccount(Account account) {
System.out.println("service层,增加账户");
}
@Override
public void deleteAccount(Integer id) {
System.out.println("service层,删除账户");
}
@Override
public void updateAccount(Account account) {
System.out.println("service层,更新账户");
}
}
在resource下新建spring的核心配置文件applicationContext.xml ,开启扫描,需要扫描service和dao层
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!--配置spring要扫描的包,其中不包括coontroller-->
<context:component-scan base-package="com.xl">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
在web.xml文件下配置监听器,让服务器运行时,触发监听器,监听器帮我们加载applicatioContext.xml配置文件
<!--配置spirng的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置spring核心配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
在AccountController下注入service实现整合
package com.xl.controller;
import com.xl.domain.Account;
import com.xl.service.impl.AccountServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/counts")
public class AccountContoller {
//注入service的实现类
@Autowired
private AccountServiceImp accountServiceImp;
//查询所有账户
@RequestMapping("/findAll")
public String findAll(){
System.out.println("web层,查询所有账户");
accountServiceImp.findAll();
return "allcounts";
}
//根据id查询账户
@RequestMapping("/findBuid")
public String findBuid(Integer id){
System.out.println("web层,根据id查询账户");
accountServiceImp.findById(id);
return "allcounts";
}
//增加账户
@RequestMapping("/insertAccount")
public String insertAccount(Account account){
System.out.println("web层,增加账户");
accountServiceImp.insertAccount(account);
return "allcounts";
}
//删除账户
@RequestMapping("/deleteAccount")
public String deleteAccount(Integer id){
System.out.println("web层,删除账户");
accountServiceImp.deleteAccount(id);
return "allcounts";
}
//修改账户
@RequestMapping("/updateAccount")
public String updateAccount(Account account){
System.out.println("web层,修改账户");
accountServiceImp.updateAccount(account);
return "allcounts";
}
}
在applicationContext.xml文件中加入mybatis的配置:连接池、sqlSessionFactory工厂、dao接口所在的包、配置事务通知、配置aop
<!--spring整合mybatis框架-->
<!--配置连接池-->
<bean id="mySql" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=Asia/Shanghai&characterEncoding=UTF8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="mySql"/>
</bean>
<!--配置AccountDao接口所在的包-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xl.dao"></property>
</bean>
<!--配置声明式事务管理-->
<!--配置事务管理-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="mySql"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<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.xl.service.impl.AccountServiceImp.*(..))"/>
</aop:config>
在dao包下新建IAccountDao接口,加上对应的sql语句注解
package com.xl.dao;
import com.xl.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Service;
import java.util.List;
public interface IAccountDao {
//查询所有账户
@Select("select * from account ")
List<Account> findAll();
//根据id查询账户
@Select("select * from where account id = #{id}")
Account findById(int id);
//增加账户
@Insert("insert into account (name,money) values (#{name},#{money}) ")
void insertAccount(Account account);
//删除账户
@Delete("delete from account where id = #{id}")
void deleteAccount(Integer id);
//修改账户信息
@Update("update account set name = #{name},money=#{money}")
void updateAccount(Account account);
}
在service中的AccountServiceImpl方法中注入dao
package com.xl.service.impl;
import com.xl.dao.IAccountDao;
import com.xl.domain.Account;
import com.xl.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImp implements IAccountService {
@Autowired
private IAccountDao iAccountDao;
@Override
public List<Account> findAll() {
System.out.println("service层,查询所有账户");
return iAccountDao.findAll();
}
@Override
public Account findById(Integer id) {
System.out.println("service层,根据id查询账户");
return iAccountDao.findById(id);
}
@Override
public void insertAccount(Account account) {
System.out.println("service层,增加账户");
iAccountDao.insertAccount(account);
}
@Override
public void deleteAccount(Integer id) {
System.out.println("service层,删除账户");
iAccountDao.deleteAccount(id);
}
@Override
public void updateAccount(Account account) {
System.out.println("service层,更新账户");
iAccountDao.updateAccount(account);
}
}
package com.xl.controller;
import com.xl.domain.Account;
import com.xl.service.impl.AccountServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/accounts")
public class AccountContoller {
@Autowired
private AccountServiceImp accountServiceImp;
//查询所有账户
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("web层,查询所有账户");
List<Account> accounts = accountServiceImp.findAll();
model.addAttribute("accounts",accounts);
return "allcounts";
}
//根据id查询账户
@RequestMapping("/findBuid")
public String findBuid(Integer id,Model model){
System.out.println("web层,根据id查询账户");
Account account = accountServiceImp.findById(id);
model.addAttribute("account",account);
return "account";
}
//增加账户
@RequestMapping("/insertAccount")
public void insertAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("web层,增加账户");
accountServiceImp.insertAccount(account);
response.sendRedirect(request.getContextPath()+"/accounts/findAll");
}
//删除账户
@RequestMapping("/deleteAccount")
public void deleteAccount(Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception{
System.out.println("web层,删除账户");
accountServiceImp.deleteAccount(id);
response.sendRedirect(request.getContextPath()+"/accounts/findAll");
}
//修改账户
@RequestMapping("/updateAccount")
public void updateAccount(Account account,HttpServletRequest request, HttpServletResponse response) throws Exception{
System.out.println("web层,修改账户");
accountServiceImp.updateAccount(account);
response.sendRedirect(request.getContextPath()+"/accounts/findAll");
}
}
在返回加载页面allcounts.jsp[中加入显示数据的代码,
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/11/13
Time: 21:09
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
h1>加载成功!!!h1><br>
<h2>所有用户数据如下:h2><br>
<c:forEach items="${accounts}" var="account">
id :${account.id}<br>
姓名:${account.name}<br>
金额:${account.money}<br>
<br>
c:forEach>
body>
html>
另外查询单个需要单独另一个页面进行显示
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/11/14
Time: 10:03
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
id为${account.id}的账户数据信息如下:<br>
姓名:${account.name}<br>
金额:${account.money}<br>
<br>
body>
html>