1.使用IntelliJ IDEA创建Mawen WEB项目
File -> New -> Project -> New Project 选择 Maven 选中 create from archetype 然后 选择 org-apache.maven.archetypes:maven-archetype-webapp
配置 maven 環境 & 新建 archetypeCatalog:internal 屬性
- 引入依賴包
mysql
mysql-connector-java
8.0.16
org.mybatis
mybatis
3.5.2
org.slf4j
slf4j-log4j12
1.7.28
junit
junit
4.12
cglib
cglib
3.1
com.alibaba
druid
1.1.20
org.mybatis
mybatis-spring
2.0.2
org.springframework
spring-jdbc
5.2.0.RELEASE
org.springframework
spring-test
5.2.0.RELEASE
org.springframework
spring-context
5.2.0.RELEASE
org.springframework
spring-web
5.2.0.RELEASE
org.springframework
spring-aop
5.2.0.RELEASE
org.springframework
spring-webmvc
5.2.0.RELEASE
org.springframework
spring-tx
5.2.0.RELEASE
org.springframework
spring-jdbc
5.2.0.RELEASE
javax.servlet
servlet-api
2.5
provided
javax.servlet.jsp
jsp-api
2.0
provided
jstl
jstl
1.2
- 准备数据(DB)
[email protected] : testdb【10:55:55】13 SQL->create database ssmdemo;
[email protected] : testdb【12:18:14】14 SQL->use ssmdemo;
[email protected] : ssmdemo【12:18:26】15 SQL->
create table account
(
id int primary key auto_increment,
name varchar(50),
money double
);
[email protected] : ssmdemo【12:18:38】16 SQL->select * from account;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | xag | 123 |
+----+------+-------+
- resources文件夹
在main文件夹下创建一个resources文件夹:右键main,new->Directory 右键新建的resources文件夹 -> Make Directory As -> Resources Root 作为资源文件夹, resources下新建META-INF目錄(Directory),META-INF里创建applicationContext.xml配置文件:new - >XML Configuration File -> Spring Config 注:右上角有个提示需要点击, 【新建sources root】右键main,new->Directory 右键新建的java文件夹 -> Make Directory As ->sources root
- 測試
5.1 Spring 測試
applicationContext.xml 文件中配置bean
創建測試代碼(com.xag 下新建 controller package,controller 下新建 HelloWord.java)
package com.xag.controller;
public class HelloWord
{
public String name;
public void setName(String name) {
this.name = name;
}
public void hello()
{
System.out.print("hello:" + name);
}
}
新建 Spring的測試類 TestHello (com.xag.test目錄下)--可以允許此類測試
package com.xag.test;
import com.xag.controller.HelloWord;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.junit.Test;
public class TestHello
{
@Test
public void run1()
{
//1.创建spring的ioc容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
//2.从ioc容器中获取bean实例
HelloWord helloWorld = (HelloWord) ctx.getBean("helloWorld");
helloWorld.hello();
}
}
5.2 Mybaits 测试
新建mybatis-config.xml 文件(resources目录下)
新建 MyMapper.xml 文件(resources/mappers目录下)
新建 log4j.properties 文件(resources目录下)
log4j.rootLogger=DEBUG,A1
log4j.logger.org.apache=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
新建Account 類(main/java 下創建com.xag.domain 和 com.xag.test)
package com.xag.domain;
import java.io.Serializable;
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 + '}';
}
}
新建TestMybatis.java( com.xag.test下),運行此類可以做測試
package com.xag.test;
import com.xag.domain.Account;
import org.junit.Test;
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 java.io.InputStream;
public class TestMybatis
{
@Test
public void run2()
{
// 获取sqlSession
SqlSession sqlSession ;
try {
// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession
sqlSession = sqlSessionFactory.openSession();
// 操作CRUD,第一个参数:指定statement,规则:命名空间+“.”+statementId
// 第二个参数:指定传入sql的参数:这里是用户id
Account user = sqlSession.selectOne("MyMapper.selectAcc", 1);
System.out.println(user);
sqlSession.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
}
}
5.3 Mybaits 测试2--使用动态代理改造CRUD
新建 AccMapper接口(com.xag.dao目錄下)
package com.xag.dao;
import com.xag.domain.Account;
import java.util.List;
public interface AccMapper
{
public Account queryAccById(Long id);
public List findAll();
public void insertAcc(Account acc);
}
新建AccMapper.xml文件(resource/mappers目錄下)
INSERT INTO account(id,name,money) VALUES (null,#{name},#{money});
全局配置文件mybatis-config.xml引入AccMapper.xml
创建TestAccMapper测试用例(com.xag.test下)
package com.xag.test;
import com.xag.dao.AccMapper;
import com.xag.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.Before;
import org.junit.Test;
import java.io.InputStream;
public class TestAccMapper
{
public AccMapper accMapper;
@Before
public void setUp() throws Exception {
// 指定配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 1. 映射文件的命名空间(namespace)必须是mapper接口的全路径
// 2. 映射文件的statement的id必须和mapper接口的方法名保持一致
// 3. Statement的resultType必须和mapper接口方法的返回类型一致
// 4. statement的parameterType必须和mapper接口方法的参数类型一致(不一定)
this.accMapper = sqlSession.getMapper(AccMapper.class);
}
@Test
public void testQueryAccById()
{
long i=1;
System.out.println(this.accMapper.queryAccById(i));
}
@Test
public void testInsertAcc() {
Account user = new Account();
user.setName("大神");
user.setMoney(500d);
this.accMapper.insertAcc(user);
System.out.println(user.getId());
}
}
- Spring 集成Mybatis
6.1. 新建 mybatis-config_spring.xml (resources目錄下) (Spring 集成Mybatis 的配置文件)
6.2 新建spring配置文件,new - >XML Configuration File -> Spring Config --> applicationContext-dao.xml(resources/spring 下)注:右上角有个提示需要点击
6.2 新建 db.properties 文件(resources/properties下)将先前的log4j.properties 也移到此目录
jdbc.driver=com.mysql.jdbc.Driver
jdbc.host=192.168.40.8
jdbc.database=ssmdemo
jdbc.userName=root
jdbc.passWord=123456
jdbc.initialSize=0
jdbc.maxActive=20
jdbc.maxIdle=20
jdbc.minIdle=1
jdbc.maxWait=3000
6.3 新建 AccountService 接口(com.xag.service目錄下)
package com.xag.service;
import com.xag.domain.Account;
import java.util.List;
public interface AccountService {
// 查询所有账户
public List findAll();
// 保存帐户信息
public void insertAcc(Account acc);
}
6.4 新建 AccountServiceImpl 實現類(com.xag.service.Impl目錄下)
package com.xag.service.Impl;
import com.xag.dao.AccMapper;
import com.xag.domain.Account;
import com.xag.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccMapper accMapper;
@Override
public List findAll() {
System.out.println("Service业务层:查询所有账户...");
return accMapper.findAll();
}
@Override
public void insertAcc(Account acc) {
System.out.println("Service业务层:保存帐户...");
accMapper.insertAcc(acc);
}
}
6.5 新建TestSpring 測試程序(com.xag.test下)
package com.xag.test;
import com.xag.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring
{
@Test
public void run3()
{
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
AccountService as = (AccountService) ac.getBean("accountService");
as.findAll();
}
}
6.6 新建 TestAccMapperSpring 測試程序(com.xag.test下)
package com.xag.test;
import com.xag.dao.AccMapper;
import com.xag.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
//目标:测试一下spring的bean的某些功能
@RunWith(SpringJUnit4ClassRunner.class)//junit整合spring的测试//立马开启了spring的注解
@ContextConfiguration(locations="classpath:spring/applicationContext-*.xml")//加载核心配置文件,自动构建spring容器
public class TestAccMapperSpring
{
@Autowired
public AccMapper accMapper;
@Test
public void testQueryAccById()
{
long i=1;
System.out.println(this.accMapper.queryAccById(i));
}
@Test
public void testFindAll() {
List accList = this.accMapper.findAll();
for (Account user : accList) {
System.out.println(user);
}
}
@Test
public void testInsertAcc()
{
Account acc = new Account();
acc.setName("大神S");
acc.setMoney(500d);
this.accMapper.insertAcc(acc);
System.out.println(acc.getId());
}
}
- SpringMVC框架代码的编写
7.1 在web.xml (webapp/WEB-INFO)中配置DispatcherServlet前端控制器
Archetype Created Web Application
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:spring/applicationContext-dao.xml
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
dispatcherServlet
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
characterEncodingFilter
/*
7.2 在resources资源文件夹中创建springmvc.xml配置文件
7.3 webapp下创建 index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
测试查询
测试包
8.5 在controller层中的AccountController的class类
package com.xag.controller;
import com.xag.domain.Account;
import com.xag.service.AccountService;
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
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/account/findAll")
public String findAll(Model model){ //存数据, Model对象
System.out.println("Controller表现层:查询所有账户...");
// 调用service的方法
List list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
@RequestMapping("/account/save")
public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService.insertAcc(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
return;
}
}
8.6 创建controller跳转的list.jsp页面了(webapp\WEB-INF\pages) 下
<%--
Created by IntelliJ IDEA.
User: Bule
Date: 2019/9/2
Time: 7:32
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" %>
Title
查询所有的账户
${account.name}
8.7 部署Tomcat进行测试
運行 index.jsp 測試tomcat 如 index.jsp 的URL 非下圖,則配置為下圖: