首页 > 其他分享 >SSM整合

SSM整合

时间:2023-02-28 11:59:11浏览次数:35  
标签:return int SSM book 整合 org import public

1、基本的项目环境搭建

1.1、准备数据库

首先建立表和数据(这里要注意就是mysql版本不一样,语句也是有变化的)

DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`  (
  `bookID` int(0) UNSIGNED NOT NULL AUTO_INCREMENT,
  `bookName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `bookCounts` int(0) NOT NULL,
  `detail` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`bookID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;

1.2、基本环境搭建

  • 新建project,添加web支持

  • 导入maven依赖关系,大概需要的包如下:

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>SSMbuild</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</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.7</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>1.16.10</version>
        </dependency>


        <!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>


    <!--静态资源导入-->
    <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>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
</project>

在Project Structure → Artifacts → Output Layout中,在WEB-INF下新建文件夹lib,在lib文件夹中添加Library File添加依赖文件

1.3、建立项目基本结构

com.wcy.controller
com.wcy.dao
com.wcy.pojo
com.wcy.service

application.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"
       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">

</beans>

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>

</configuration>

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">

</web-app>

2、整合Mybatis

2.1、数据库配置文件

#如果是mysql 8.0以上drive需要这个cj
jdbc.driver=com.mysql.cj.jdbc.Driver
#如果是mysql 8.0以上的需要加上时区设置
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=12345

IDEA连接数据库,这样就可以保证数据库能够连接

2.2、 编写MyBatis的核心配置文件: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>
    <typeAliases>
        <package name="com.wcy.pojo"/>
    </typeAliases>


    <mappers>
        <mapper class="com.wcy.dao.BookMapper"/>
    </mappers>


</configuration>

2.3、编写对应的实体类,com.wcy.pojo.Books,这里用到了lombok工具

package com.wcy.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

2.4、编写实体类对应的mapper

package com.wcy.dao;
import com.wcy.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
    int addBook(Books book);


    int delBookById(@Param("bookId") int id);


    int updateBook(Books book);


    Books queryBookById(int id);


    List<Books> queryAllBooks();
}

2.5、编写对应的mapper.xml

<?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.wcy.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>


    <delete id="delBookById" parameterType="int">
        delete from ssmbuild.booksm where bookID = ${bookID};
    </delete>


    <update id="updateBook" parameterType="Books">
        update ssmbuild.booksm
        set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail}
         =  where bookID = #{bookID} ;
    </update>
    
    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.booksm where bookID = #{bookID};
    </select>


    <select id="queryAllBooks" resultType="Books">
        select * from ssmbuild.books;
    </select>
</mapper>

dao层准备完毕

2.6、编写service接口和实现类

BookService接口

package com.wcy.service;

import com.wcy.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService {
    int addBook(Books book);

    int delBookById(int id);

    int updateBook(Books book);

    Books queryBookById(int id);

    List<Books> queryAllBooks();
}

BookServiceImpl类

package com.wcy.service;

import com.wcy.dao.BookMapper;
import com.wcy.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;


public class BookServiceImpl implements BookService{

    private BookMapper bookMapper;

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

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

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

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

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

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

3、整合Spring

3.1、Spring整合Mybatis

spring-dao.xml,实现连接数据库,自动将dao接口(mapper)注入到容器中

点击查看代码
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--1、关联数据库文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--2、数据库连接池
    dbcp: 半自动操作
    c3p0: 自动化操作(自动化加载配置,并且可以自动设置到对象中-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

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

    <!--4、配置dao接口扫描包,动态实现Dao接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--mapper类如果继承了SqlSessionDaoSupport-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--配置扫描的dao包-->
        <property name="basePackage" value="com.w

cy.dao"/>
    </bean>

</beans>

3.2、Spring整合Service

spring-service.xml,配置service,将自动注入容器里的mapper给service实现类

<?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.wcy.service"/>

    <!--2. 将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
    <bean id="BookServiceImpl" class="com.wcy.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--3. 声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--4. aop事务支持-->

</beans>

4、整合SpringMVC

4.1、web.xml,主要做的注册servlet、匹配请求等

点击查看代码
<?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-->
    <servlet>
        <servlet-name>SpringMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联一个SpringMvc的配置文件:【servlet-name】-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--启动级别1-->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <!--匹配所有请求(不包括jsp)-->
    <servlet-mapping>
        <servlet-name>SpringMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!--乱码过滤-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern><!--这里有个坑,就是/*才能包括得了jsp,因为加了jsp过滤器 -->
    </filter-mapping>


    <!--session-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

4.2、Spring-MVC.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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--让springMVC不处理静态资源,css,js什么的-->
    <mvc:default-servlet-handler/>


    <!--支持mvc注解驱动-->
    <mvc:annotation-driven/>


    <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.wcy.controller"/>


    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>


    <!--乱码问题-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

4.3、applicationContext.xml,关联所有的配置文件,在编译器里面可以点击加入统一的Moduls,或者在配置文件里import

点击查看代码
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">


    <context:annotation-config />
    <!--将配置文件关联-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
    <!--扫描service下的包-->
    <context:component-scan base-package="com.wcy.service"/>


    <!--2、将所有的业务类,注入到spring容器当中,可以通过配置或注解实现,这里因为dao自动装配了,所以不用生命bean-->
    <bean id="BookServiceImpl" class="com.wcy.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

</beans>

配置文件结束了,那么开始编写对应文件里面的controller、页面(一般来说是先写完controller再写配置文件)

4.4、控制层和页面

BookController类

点击查看代码
package com.wcy.controller;


import com.wcy.pojo.Books;
import com.wcy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;


@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;


    //查询全部书籍并且返回到书籍展示页面
    @RequestMapping("/allBooks")
    public String list(Model model) {
        List<Books> books = bookService.queryAllBooks();
        model.addAttribute("list",books);
        return "allBook";
    }


    //跳转到添加书籍界面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }


    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books book) {
        System.out.println(book.toString());
        bookService.addBook(book);
        return "redirect:/book/allBooks"; //重定向到首页
    }


    //跳转到修改界面
    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(int id,Model model) {
        Books book = bookService.queryBookById(id);
        model.addAttribute("QBook",book);
        return "updateBook";
    }


    //修改书籍信息
    @RequestMapping("/updateBook")
    public String UpdatePaper(Books book) {
        bookService.updateBook(book);
        return "redirect:/book/allBooks";
    }


    //删除数据
    @RequestMapping("/deleteBook/{bookID}")
    public String delPaper(@PathVariable("bookID") int id) {
        System.out.println("deleteBook-->" + id);
        bookService.delBookById(id);
        return "redirect:/book/allBooks";
    }


    //查询书籍queryBook
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model) {
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        if(books == null) {
            list = bookService.queryAllBooks();
            model.addAttribute("error","未查到");
        }


        list.add(books);
        model.addAttribute("list",list);
        return "allBook";
    }
}

建立对应视图解析器的文件夹和页面

allbooks.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 --%>
    <%--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="path-header">
                <h1>
                    <small>书籍列表 —— 显式所有书籍</small>
                </h1>
            </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 class="col-md-4 column"></div>
            <div class="col-md-4 column">
                <%--查询书籍--%>
                <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook"  method="post" style="float: right">
                    <span style="color: red;font-weight: bold">${error}</span>
                    <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    <input type="submit" value="查询" class="btn btn-primary">
                </form>
            </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>
                    <th>操作</th>
                </tr>
                </thead>


                <%--书籍从数据库中查询出来,从这个list中遍历出来:foreach--%>
                <tbody>
                <c:forEach var="book" items="${requestScope.get('list')}">  <%--jstl语句--%>
                    <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>
                            &nbsp; | &nbsp; <%--空格 竖线 空格--%>
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

addbooks.jsp

点击查看代码
<%--
  Created by IntelliJ IDEA.
  User: 86155
  Date: 2022/3/27
  Time: 18:51
  To change this template use File | Settings | File Templates.
--%>
<%@ 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 --%>
    <%--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="path-header">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        <div class="form-group">
            <label for="bkName">书籍名称:</label>
            <input type="text" name="bookName" class="form-control" id="bkName" required>
        </div>
        <div class="form-group">
            <label for="bkCount">书籍数量:</label>
            <input type="text" name="bookCounts" class="form-control" id="bkCount" required>
        </div>
        <div class="form-group">
            <label for="bkDetail">书籍描述:</label>
            <input type="text" name="detail" class="form-control" id="bkDetail" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="添加">
        </div>
    </form>
</div>
</body>
</html>

5、Ajax

5.1、iframe标签

test.html,iframe标签实现页面嵌套,可以做到只改变嵌套里的内容,不改变外部元素

点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <meta charset="UTF-8">
    <title>iframe</title>
    <script>
        function go() {
            var url = document.getElementById("url").value;
            document.getElementById("iframe1").src=url;
        }
    </script>
</head>
<body>
<div>
    <p>请输入地址:</p>
    <p>
        <input type="text" id="url" value="请输入网址">
        <input type="button" value="提交" onclick="go()">
    </p>


</div>
<div>
    <iframe id="iframe1" frameborder="0" style="width: 100%;height: 500px"></iframe>
</div>


</body>
</html>

5.2、JQuery Ajax

导入JQuery前,要过滤静态资源,否则jQuery.js文件无效

点击查看代码
<!--让springMVC不处理静态资源,css,js什么的-->
<mvc:default-servlet-handler/>

index.jsp,刷新处理数据交给Ajax,后端只负责返回数据,前后端分离

<%--
  Created by IntelliJ IDEA.
  User: 86155
  Date: 2022/3/28
  Time: 20:43
  To change this template use File | Settings | File Templates.
--%>
<%@ 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}/a1",
          data:{"name":$("#username").val()},
          success:function (data) {
            alert(data);
          },
          error:function () {
            console.log()
          }
        })
      }
    </script>
  </head>
  <body>
  用户名<input type="text" id="username" onblur="a()">
  </body>
</html>

5.3、Ajax加载数据

因为JS文件不知道为什么加载不了,所以这里贴老师的代码

简单的来说就是id为“btn”的按钮被点击后触发事件,触发后发起post请求,这里是简写,只有url和success,成功后对数据进行处理,加入html中,再放到显示的地方。


6、拦截器

6.1、概述

拦截器类似于之前防止乱码的过滤器Filter,用于对请求进行预处理和后处理。

与过滤器不同的地方在于,拦截器是具体的AOP思想的运用

拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
拦截器只会拦截访问的控制器方法,如果访问的是jsp、html、css、image、js是不会拦截的

6.2、实现

实现的方法很简单,实现HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {
    //return true; 执行下一个拦截器,false不能进入
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("处理前");
        return true;
    }


    //一般用来写拦截日志
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("处理后");
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("清理");
    }
}

配置拦截器

<mvc:interceptors>
    <mvc:interceptor>
        <!--包括当前请求前缀下的所有请求-->
        <mvc:mapping path="/**"/>
        <bean class="com.wcy.config.MyInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

6.3、未登录拦截实例

登陆拦截器,去登陆界面和提交登陆请求放行,session中有用户名信息放行,其余都得去登陆界面

public class LoginInterceptor implements HandlerInterceptor {
    //判断什么情况下登陆
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getRequestURI().contains("goLogin")) {
            return true;
        }

        if(request.getRequestURI().contains("login")) {
            return true;
        }

        if (request.getSession() != null && request.getSession().getAttribute("userLoginInfo") != null) {
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }
}

配置文件配置拦截器

mvc:interceptors
mvc:interceptor

<mvc:mapping path="/"/>

</mvc:interceptor>
mvc:interceptor
<mvc:mapping path="/user/
"/>

</mvc:interceptor>
</mvc:interceptors>

控制器

点击查看代码
@Controller
@RequestMapping("/user")
public class LoginController {


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

    @RequestMapping("/main")
    public String main() {
        return "Main";
    }

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

    @RequestMapping("/goOut")
    public String goOut(HttpSession session) {
        //销毁session session.invalidate();
        //移除session属性
        session.removeAttribute("userLoginInfo");
        return "login";
    }
}

index.jsp

点击查看代码
<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>

login.jsp

点击查看代码
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录界面</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    用户名:<input type="text" name="username">
    密码:<input type="text" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

Main.jsp

点击查看代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<span>欢迎你,${username}</span>
<p>
    <a href="${pageContext.request.contextPath}/user/goOut">注销</a>
</p>
</body>
</html>

这样就做到了登陆验证拦截






标签:return,int,SSM,book,整合,org,import,public
From: https://www.cnblogs.com/wcyblogs/p/17163512.html

相关文章

  • 【spring笔记】Spring整合Mybaties
    官方文档:http://mybatis.org/spring/zh/sqlsession.html1、实现方式1核心思想:利用Spring配置依赖注入创建sqlSessionFactory和sqlSession实例需要的包如下:1.1、编......
  • SSM框架-MyBatis学习日记4
    日志工厂如果一个数据库相关的操作出现了问题,我们可以根据输出的SQL语句快速排查问题。对于以往的开发过程,我们会经常使用到debug模式来调节,跟踪我们的代码执行过程。但......
  • SSM框架-MyBatis学习日记3
    配置解析mybatis-config.xml系统核心配置文件MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。能配置的内容如下:configuration(配置)properties(属性......
  • SSM框架-MyBatis学习日记2
    在上一篇的日记中,我成功搭建了MyBatis的工作环境,至此只需要通过配置UserMapper和UserMapper.xml即可完成对数据库的增删查改工作。以下是UserMapper.xml中配置的部分:<?xm......
  • SSM jsp人力资源管理系统
    SSMjsp人力资源管理系统登录系统管理部门管理员工管理薪资管理招聘管理培训管理分页列表展示搜索新增编辑删除系统介绍:权限分为管理员和普通员工普通员工仅......
  • 整合Junit5
    1、引入依赖<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5......
  • 如何将 Autofac 整合进 Net6.0 Core MVC 项目中
    一、前言1、前言Asp.NetCoreMvc,我也用了很长一段时间了,它现在的编程模型和方式还是特别棒的,都是组件开发,什么都可以替换,当然了,您别抬杠,有些还是......
  • SSM
    Spring1、Spring框架的好处1、轻量级2、MVC框架3、面向切面编程4、控制反转2、解释一下什么是AOPAOP:面向切面编程。我的理解就是和业务核心逻辑的无关,但是可以为在......
  • rabbitmq的启动命令和springboot整合使用rabbitmq
    环境:windows安装erlang和rabbitmq的过程这里不多说,记得两个的版本要对应。1.启动rabbitmq:进入sbin目录:其中可能报错:则需要终止已经开始的进程(可能是之前启动过)tasklist|......
  • 整合log4j
    引入依赖<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency> resources目录......