1.新建maven项目,添加web支持
2.导包
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.20</version>
</dependency>
</dependencies>
<!--在build中配置resources来防止资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3、新建mybatis-config.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>
<settings>
<!--mybatis标准sql日志输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
4.web.xml中添加配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 使用默认servlet处理静态资源请求 -->
<!--后缀名为css/gif/jps/png/js的静态资源不拦截,解决【jsp中的图片不显示】的问题-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<!--设置session一分钟后自动销毁-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<!-- 处理请求或者响应的字符集过滤器(用于处理中文乱码的问题的) -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Spring的核心控制器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 加载Spring的配置文件(可能有多个需加载,统一命名,已applicationContext为开头的xml) -->
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- 配置SpringMVC的核心控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载SpringMVC配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
<!--springmvc.xml是springmvc的配置文件,当存在多个配置文件时,这里必须配置总的配置文件-->
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- servlet中的name与servlet-mapping中name的一样 /只匹配请求 /*jsp页面也匹配-->
<!-- /只匹配请求 /*jsp页面也匹配-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
5、新建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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.jiang"/>
<!-- ************************************************************************************ -->
<import resource="springmvc-servlet.xml"/>
<!-- 事务管理:注解方式实现,在需要事务管理的方法上添加@Transactional -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource1"/>
<property name="rollbackOnCommitFailure" value="true"/>
</bean>
<!-- 使用@Transactional进行声明式事务管理需要声明下面这行,使Spring事物管理的注解生效-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<!-- ************************************************************************************ -->
<!--3 会话工厂bean sqlSessionFactoryBean -->
<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource1"/>
<!-- sql映射文件路径:mapper.xml文件 -->
<property name="mapperLocations" value="classpath*:com/jiang/dao/*.xml"/>
<!-- 别名 -->
<!--<property name="typeAliasesPackage" value="com.baosight.uacs.common.config.mybatis.entities"/>-->
<!--<property name="typeAliases" value="com.baosight.uacs.common.config.mybatis.entities.Book"/>-->
<!--引用mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 3.2 配置mysql数据源信息 -->
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://192.168.0.110:3306/UACS?useUnicode=true&characterEncoding=utf-8" />
<property name="user" value="root" />
<property name="password" value="uacsapp" />
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- ************************************************************************************ -->
<!--4 自动扫描对象关系映射,替代了mybatis的映射器:注册sqlMapper文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
<!--<property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>-->
<!-- 指定要自动扫描接口的基础包,实现接口 -->
<property name="basePackage" value="com.jiang.dao"/>
</bean>
<!-- ************************************************************************************ -->
</beans>
6、新建springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 让springmvc不处理静态资源 .css .js .html .mp3 .mp4等 -->
<mvc:default-servlet-handler/>
<!-- 使SpringMVC注解生效 :会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置视图解析器 -->
<!-- 视图解析器开启到的情况下,提高了安全性,浏览器无法直接查看WEB-INF下的文件。跳转时jsp文件不需要后缀,如访问/index.jsp,写login就行 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
7.写pojo、dao、service、controller四层代码、并在WEB-INF下新建jsp文件夹,写jsp页面
1.pojo:Books
package com.jiang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Repository;
@Repository
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookId;
private String bookName;
private int bookCounts;
private String detail;
}
2.dao:BookMapper、BookMapper,xml
package com.jiang.dao;
import com.jiang.pojo.Books;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookMapper {
int addBook(Books books);
int deleteBookById(@Param("bookId") int id);
int updateBook(Books books);
Books selectBookById(@Param("bookId") int id);
List<Books> seletAllBooks();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:接口的全类名,与dao的接口类对应 -->
<mapper namespace="com.jiang.dao.BookMapper">
<insert id="addBook" parameterType="com.jiang.pojo.Books">
insert into jx_books(bookName,bookCounts,detail) VALUES(#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
delete from jx_books where bookId = #{bookId}
</delete>
<update id="updateBook" parameterType="com.jiang.pojo.Books">
update jx_books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookId=#{bookId}
</update>
<select id="selectBookById" resultType="com.jiang.pojo.Books">
select * from jx_books where bookId=#{bookId}
</select>
<select id="seletAllBooks" parameterType="int" resultType="com.jiang.pojo.Books">
select * from jx_books
</select>
</mapper>
3.service:BookService、BookServiceImpl
package com.jiang.service;
import com.jiang.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
int addBook(Books books);
int deleteBookById(int id);
int updateBook(Books books);
Books selectBookById(int id);
List<Books> seletAllBooks();
}
package com.jiang.service.impl;
import com.jiang.dao.BookMapper;
import com.jiang.pojo.Books;
import com.jiang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
@Transactional
public int updateBook(Books books) {
Books books1 = bookMapper.selectBookById(1);
books1.setBookCounts(books1.getBookCounts()+100);
bookMapper.updateBook(books1);
//int a=2/0;//事务管理:当这里出现错误时,+100会被回滚。当都正常时才会被提交
return bookMapper.updateBook(books);
}
@Override
public Books selectBookById(int id) {
return bookMapper.selectBookById(id);
}
@Override
public List<Books> seletAllBooks() {
return bookMapper.seletAllBooks();
}
}
4.controller:BookController
package com.jiang.controller;
import com.alibaba.fastjson2.JSON;
import com.jiang.pojo.Books;
import com.jiang.service.BookService;
import com.jiang.service.impl.BookServiceImpl;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Controller
@RequestMapping(value = "book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("toAddBook")
public String toAddBook() {
return "addBook";
}
@RequestMapping("addBook")
public String addBook(Books books) {
int i = bookService.addBook(books);
System.out.println("新增结果="+i);
return "forward:seletAllBooks";
}
@RequestMapping("deleteBookById/{id}")
public String deleteBookById(@PathVariable int id) {
int i = bookService.deleteBookById(id);
System.out.println("删除结果="+i);
return "forward:/book/seletAllBooks";
//return "redirect:/book/seletAllBooks";//请求转发也可以
//return "forward:seletAllBooks";//这个就不行
}
@RequestMapping("toUpdateBook")
public String toUpdateBook(int id,Model model) {
Books books = bookService.selectBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
@RequestMapping("updateBook")
public String updateBook(Books books) {
int i = bookService.updateBook(books);
System.out.println("修改结果="+i);
return "forward:seletAllBooks";
}
@RequestMapping("seletAllBooks")
public String seletAllBooks(Model model) {
List<Books> books = bookService.seletAllBooks();
for (Books book : books) {
System.out.println(book.toString());
}
model.addAttribute("list",books);
return "allbook";
}
}
5.Test
import com.jiang.pojo.Books;
import com.jiang.service.BookService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Mtest {
@Test
public void MyTest1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookServiceImpl = context.getBean("bookServiceImpl", BookService.class);
List<Books> books = bookServiceImpl.seletAllBooks();
for (Books book : books) {
System.out.println(book.toString());//通过这个方法直接测试bookServiceImpl对象是否创建成功
}
}
}
6.JSP
allbook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表 —— 显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名字</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookId()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookId()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/deleteBookById/${book.getBookId()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
updateBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改信息</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改信息</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookId" value="${book.getBookId()}"/>
书籍名称:<input type="text" name="bookName" value="${book.getBookName()}" required/>
书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}" required/>
书籍详情:<input type="text" name="detail" value="${book.getDetail() }" required/>
<input type="submit" value="提交"/>
</form>
</div>
自带的index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/12/1/001
Time: 20:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>我是主页面</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/seletAllBooks">全部书籍
</a>
</h3>
<br>
</body>
</html>
7、sql
CREATE TABLE `jx_books` (
`bookId` int(11) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` varchar(100) DEFAULT NULL COMMENT '书名',
`bookCounts` int(11) DEFAULT NULL COMMENT '数量',
`detail` varchar(200) DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`bookId`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
INSERT INTO UACS.jx_books (bookName,bookCounts,detail) VALUES
('一元',950,'一元为一元,学艺看眼前'),
('两极',1010,'两极生四象,四象生八卦'),
('三体',1220,'三体成世界,自有大方圆'),
('四季',20,'四季烟火,最富人心'),
('五行',50,'五行八卦,最是无情'),
('7德国法国20',5020,'20');
8、常见问题
1.通配符的匹配很全面, 但无法找到元素:applicationContext.xml配置文件头元素有缺失
2.新导入的包,记得在项目属性中添加到项目lib目录下
3.多个配置文件时,记得进行文件引用,保证web.xml能扫描到