SSM基础环境搭建

maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?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>com.tang</groupId>
<artifactId>SSM</artifactId>
<version>1.0-SNAPSHOT</version>

<!-- junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring -->
<dependencies>
<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>
<!-- jsp、servlet -->
<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.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.6</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>

<!-- 约定大于配置 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

resources配置文件

  • mybatis-config.xml(MyBatis核心配置文件)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?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>
    <typeAliases>
    <package name="com.tang.pojo"/>
    </typeAliases>
    </configuration>
  • db.properties(数据库连接)

    错错错,就是这一步导致后续数据库连接出错,我这里原本使用以前配置文件的写法,然而以前文件是默认jdbc,现在使用的是c3p0连接池,这里使用username就会出问题,估计是哪里冲突了,但具体原因没有检测出来。解决方法有二,可以直接带前缀如jdbc、jb等好像是无限制,或者使用连接池定义的变量名,例如c3p0是driverClass、jdbcUrl、user、password。

    1
    2
    3
    4
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
    username=root
    password=111111

    正确写法!!!

    1
    2
    3
    4
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=111111
  • applicationContext.xml(Spring核心配置文件)

    1
    2
    3
    4
    5
    6
    7
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    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">

    </beans>

MyBatis层

pojo实体类

1
2
3
4
5
6
7
8
9
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}

dao接口及sql语句(Mapper)

  • Mapper

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public interface BookMapper {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(@Param("bookID") int id);
    //修改一本书
    int updateBook(Books books);
    //查询一本书
    Books queryBookById(@Param("bookID") int id);
    //查询全部的书
    List<Books> queryAllBooks();
    }
  • Mapper.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.tang.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
    insert into ssmbuild.books (bookName,bookCounts,detail)
    value(#{bookName},#{bookCounts},#{detail});
    </insert>
    <delete id="deleteBookById" parameterType="int">
    delete from books where bookID = #{bookID};
    </delete>
    <update id="updateBook" parameterType="Books">
    update ssmbuild.books
    set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
    where bookID = #{bookID};
    </update>
    <select id="queryBookById" resultType="Books" parameterType="bookID">
    select * from ssmbuild.books
    where bookID = #{bookID};
    </select>
    <select id="queryAllBooks" resultType="Books">
    select * from ssmbuild.books;
    </select>
    </mapper>

别忘了去配置文件注册Mapper

1
2
3
<mappers>
<mapper class="com.tang.dao.BookMapper"/>
</mappers>

service调用dao,实现业务操作

  • Service

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public interface BookService {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(int id);
    //修改一本书
    int updateBook(Books books);
    //查询一本书
    Books queryBookById(int id);
    //查询全部的书
    List<Books> queryAllBooks();
    }
  • ServiceImpl(具体实现类)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    //service层调用dao层的方法,传值进去进行具体实现
    public class BookServiceImpl implements BookService{
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
    this.bookMapper = bookMapper;
    }

    public int addBook(Books books) {
    return bookMapper.addBook(books);
    }

    public int deleteBookById(int id) {
    return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
    return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
    return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBooks() {
    return bookMapper.queryAllBooks();
    }
    }

Spring层(整合dao和service)

  • spring-dao.xml(可使用各种连接池)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 关联数据库配置文件 -->
    <context:property-placeholder location="db.properties"/>
    <!-- 连接池c3p0 自动化操作 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${driver}"/>
    <property name="jdbcUrl" value="${url}"/>
    <property name="user" value="${username}"/>
    <property name="password" value="${password}"/>
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 配置dao接口扫描包,动态实现dao接口可以注入到Spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <property name="basePackage" value="com.tang.dao"/>
    </bean>
    </beans>
  • spring-service.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描service下的包-->
    <context:component-scan base-package="com.tang.service"/>
    <!-- 业务类注入Spring -->
    <bean id="BookServiceImpl" class="com.tang.service.BookServiceImpl">
    <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!-- 声明式事务配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"/>
    </bean>

    </beans>

SpringMVC层

  • 首先添加Web项目

  • 配置web.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <?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">
    <!-- DispatchServlet -->
    <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 乱码过滤 -->
    <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 15分钟自动过期 -->
    <session-config>
    <session-timeout>15</session-timeout>
    </session-config>
    </web-app>
  • spring-mvc.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 静态资源过滤 -->
    <mvc:default-servlet-handler/>
    <!-- 扫描包:controller -->
    <context:component-scan base-package="com.tang.controller"/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    </beans>
  • 然后检查一下war包的lib目录是否导入,记得换war包输出路径,方便maven管理,最后记得配置tomcat


实现简单功能

展示全部书籍

  • controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Controller
    @RequestMapping("/book")
    public class BookController {
    //controller调用service
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍,并返回书记展示界面
    @RequestMapping("/allBook")
    public String list(Model model){
    List<Books> list = bookService.queryAllBooks();
    model.addAttribute("list",list);
    return "allBook";
    }
    }
  • 编写首页

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>首页</title>
    <style>
    a{
    text-decoration: none;
    color: deeppink;
    font-size: 18px;
    }
    h3{
    width: 180px;
    height: 38px;
    margin: 100px auto;
    text-align: center;
    line-height: 38px;
    background: darkturquoise;
    border-radius: 5px;
    }
    </style>
    </head>
    <body>

    <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">进入书籍展示</a>
    </h3>

    </body>
    </html>
  • 编写查询页,外部导入CDN使用bootstrap自带格式,然后编写前端界面,使用jstl的c标签(要导入头部),其中用foreach遍历书籍列表,然后展示

    bootstrap:https://v3.bootcss.com/,CDN网上搜,这里使用的是3.3.7比较稳定

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>书籍展示</title>
    <link href="https://cdn.staticfile.org/twitter-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-head">
    <h2>书籍列表 ———— 显示全部书籍</h2>
    </div>
    </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>
    </tr>
    </thead>

    <tbody>
    <c:forEach var="book" items="${list}">
    <tr>
    <td>${book.bookID}</td>
    <td>${book.bookName}</td>
    <td>${book.bookCounts}</td>
    <td>${book.detail}</td>
    </tr>
    </c:forEach>
    </tbody>
    </table>
    </div>
    </div>
    </div>

    </body>
    </html>
  • 结果

4.png

添加书籍

  • controller

    其中addBook即添加界面,add会重定向到查询页

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RequestMapping("/addBook")
    public String addPage(){
    return "addBook";
    }

    @RequestMapping("/add")
    public String addBook(Books books){
    System.out.println("logggggg:"+books);
    bookService.addBook(books);
    return "redirect:/book/allBook";//重定向
    }
  • 在书籍展示界面新增添加功能

    1
    2
    3
    4
    5
    <div class="row">
    <div class="col-md-4 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook">添加新书</a>
    </div>
    </div>
  • 编写书籍添加界面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>新增书籍</title>
    <link href="https://cdn.staticfile.org/twitter-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-head">
    <h2>书籍列表 ———— 新增书籍</h2>
    </div>
    </div>
    </div>
    <%--表单提交至add,add重定向查询页--%>
    <form action="${pageContext.request.contextPath}/book/add" method="post">
    <div class="form-group">
    <label>书籍名称:</label>
    <input type="text" name="bookName" class="form-control" required>
    </div>
    <div class="form-group">
    <label>书籍数量:</label>
    <input type="text" name="bookCounts" class="form-control" required>
    </div>
    <div class="form-group">
    <label>书籍描述:</label>
    <input type="text" name="detail" class="form-control" required>
    </div>
    <div class="form-group">
    <input type="submit" class="form-control" value="添加">
    </div>
    </form>

    </div>

    </body>
    </html>

删除修改

  • 在书籍展示的表格中,为每一本书添加删除与修改的功能

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <tbody>
    <c:forEach var="book" items="${list}">
    <tr>
    <td>${book.bookID}</td>
    <td>${book.bookName}</td>
    <td>${book.bookCounts}</td>
    <td>${book.detail}</td>
    <td>
    <a href="${pageContext.request.contextPath}/book/updateBook?id=${book.bookID}">修改</a>
    &nbsp; | &nbsp;
    <a href="${pageContext.request.contextPath}/book/delete?id=${book.bookID}">删除</a>
    </td>
    </tr>
    </c:forEach>
    </tbody>
  • controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @RequestMapping("/updateBook")
    public String updatePage(Model model,int id){
    Books books = bookService.queryBookById(id);
    model.addAttribute("findBook",books);
    return "updateBook";
    }

    @RequestMapping("/update")
    public String updateBook(Books books){
    bookService.updateBook(books);
    return "redirect:/book/allBook";
    }

    @RequestMapping("/delete")
    public String deleteBook(int id){
    bookService.deleteBookById(id);
    return "redirect:/book/allBook";
    }
  • 修改的界面,删除直接删就不用界面了

    注意,修改的sql是需要id的,所以我们隐性传递一个id,也就是当前要修改对象的原本id

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>书籍修改</title>
    <link href="https://cdn.staticfile.org/twitter-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-head">
    <h2>修改书籍</h2>
    </div>
    </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/update" method="post">
    <%-- 隐藏传一个id,因为update的sql语句时根据id修改的,我们传值时要带id --%>
    <input type="hidden" name="bookID" value="${findBook.bookID}">
    <div class="form-group">
    <label>书籍名称:</label>
    <input type="text" name="bookName" class="form-control" value="${findBook.bookName}" required>
    </div>
    <div class="form-group">
    <label>书籍数量:</label>
    <input type="text" name="bookCounts" class="form-control" value="${findBook.bookCounts}" required>
    </div>
    <div class="form-group">
    <label>书籍描述:</label>
    <input type="text" name="detail" class="form-control" value="${findBook.detail}" required>
    </div>
    <div class="form-group">
    <input type="submit" class="form-control" value="修改">
    </div>
    </form>

    </div>

    </body>
    </html>

搜索查询(添加底层功能,加接口)

  • dao层Mapper新增接口方法

    1
    Books queryBookByName(@Param("bookName") String bookName);
  • Mapper.xml实现对应sql语句

    1
    2
    3
    <select id="queryBookByName" resultType="Books">
    select * from ssmbuild.books where bookName = #{bookName};
    </select>
  • service业务层Service新增接口方法

    1
    Books queryBookByName(String bookName);
  • ServiceImpl实现新方法

    1
    2
    3
    public Books queryBookByName(String bookName){
    return bookMapper.queryBookByName(bookName);
    }
  • controller调用Service

    复用allBook界面,只传递展示搜索值

    1
    2
    3
    4
    5
    6
    7
    8
    @RequestMapping("/queryBook")
    public String queryBook(Model model,String queryBookName){
    Books books = bookService.queryBookByName(queryBookName);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    model.addAttribute("list",list);
    return "redirect:/book/allBook";
    }
  • 前端页面

    新增查询,且添加显示全部书籍功能,以便查询无结果返回展示页。

    最后页面返回还是allBook界面,但我们只传入了被搜索元素,故查询后的前端界面可复用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <div class="row">
    <div class="col-md-4 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook">添加新书</a>
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
    </div>
    <div class="col-md-8 column">
    <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
    <input type="text" name="queryBookName">
    <input type="submit" value="查询" class="btn btn-primary">
    </form>
    </div>
    </div>

Ajax

Asynchronous javascript And Xml(异步JavaScript和XML),ajax可以快速将增量更新呈现到用户界面上,而不需要重载整个页面,使得程序能更快回应用户的操作,就像我博客中的底部音乐播放器,这个就是使用了ajax,没使用时每次切换页面都会重加载,导致歌曲不能持续播放。使用后切换页面时音乐便不会中断。

使用JQuery库的Ajax开发,前后端分离的重要点。https://www.w3school.com.cn/jquery/ajax_ajax.asp

就是携带一些参数去请求响应,前后端对应。

简单练习1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a",
data:{"name":$("#username").val()},
success: function (data) {
alert(data)
}
})
}
</script>
</head>
<body>

用户名:<input type="text" id="username" onblur="a()">

</body>
</html>

1
2
3
4
5
6
7
8
9
@RequestMapping("/a")
public void a(String name, HttpServletResponse response) throws IOException {
System.out.println("a:"+name);
if("aidian".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}

简单练习2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>

<script>
function a1() {
$.post({
url:"${pageContext.request.contextPath}/a2",
data:{"name":$("#name").val()},
success:function (data) {
console.log(data);
$("#userInfo").css("color","blue");
$("#userInfo").html(data);
}
});
}
function a2() {
$.post({
url:"${pageContext.request.contextPath}/a2",
data:{"pwd":$("#pwd").val()},
success:function (data) {
console.log(data);
$("#pwdInfo").css("color","red");
$("#pwdInfo").html(data);
}
});
}
</script>
</head>
<body>

<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码:<input type="password" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>

</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("/a2")
public String a2(String name,String pwd){
String msg="";
if(name != null){
if("admin".equals(name)){
msg="OK";
}else {
msg="姓名NO";
}
}
if(pwd != null){
if("admin".equals(pwd)){
msg="OK";
}else {
msg="密码NO";
}
}
return msg;
}

拦截器Interceptor

AOP思想!练习一个简单的练习,进首页必须登录。

也就是说我们要给session传递参数,当session中有相应参数时我们才能通过拦截器进入首页,就和我们平时网站登录一样,只有登录后才可通过拦截器获取更高的权限。

LoginInterceptor实现handlerIntercepter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class logininterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//设置一个拦截,未登录不能进入首页
HttpSession session = request.getSession();
//登录放行
if(session.getAttribute("userLoginInfo")!=null){
return true;
}
//登录界面,可跳转首页
if(request.getRequestURI().contains("login")){
return true;
}

//未登录则跳转首页
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}

LoginController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Controller
@RequestMapping("/user")
public class LoginController {
@RequestMapping("/main")
public String main(){
return "main";
}

@RequestMapping("/gologin")
public String gologin(){
return "login";
}

@RequestMapping("/login")
public String login(HttpSession session, String username, String password){
session.setAttribute("userLoginInfo" ,username);
return "main";
}
}

登录界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="提交">
</form>

</body>
</html>

首页

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>

<h1><a href="${pageContext.request.contextPath}/user/gologin">登录界面</a></h1>
<h1><a href="${pageContext.request.contextPath}/user/main">首页</a></h1>

</body>
</html>

记得在配置文件中添加配置

1
2
3
4
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="com.tang.config.logininterceptor"/>
</mvc:interceptor>

文件上传、下载

Spring中自带文件上传,我们直接在配置文件中添加

1
2
3
4
5
6
<!-- 使用Spring自带的文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>

FileController

这里我们先上传图片到upload,然后就可以在download中下载了,下载的图片是我们规定好的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@Controller
public class FileController {
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
String uploadFileName = file.getOriginalFilename();
if("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传的文件名:"+uploadFileName);

String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件的保存路径:"+realPath);

InputStream is = file.getInputStream();
OutputStream os =new FileOutputStream(new File(realPath,uploadFileName));

int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer)) != -1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}

@RequestMapping("/download")
public String fileDownload(HttpServletResponse response,HttpServletRequest request) throws IOException {
String path = request.getServletContext().getRealPath("/upload");
String fileName = "1.png";

response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));

File file = new File(path,fileName);
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer)) != -1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return null;
}
}

前端表单上传、下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="upload">
</form>

<a href="${pageContext.request.contextPath}/download">下载</a>

</body>
</html>


小结

xdm,准备写项目了,先看看深浅,耗时太久我就先复习基础去找个小实习,然后慢慢搞项目。