【狂神说Java】SpringMVC详细笔记(全)

文章目录

  • 一、什么是SpringMVC
    • 1.1、springmvc-01-serlvet模块
      • 1、模块
      • 2、添加Web app的支持!
      • 3、pom.xml (springmvc-01-serlvet)
      • 4、HelloServlet
      • 5、test
      • 6、web
      • 7、from
      • 8、结果
    • 1.2、MVC框架要做哪些事情
    • 1.3、文档
    • 1.4、注意
  • 二、第一个MVC程序
    • 1.1、springmvc-02-hellomvc
      • 1、模块
      • 2、web.xml
      • 3、springmvc-servlet.xml
      • 4、HelloController.java
      • 5、Configurations配置
      • 6、查看Project Structure
      • 7、结果
    • 1.2、中心控制器
    • 1.3、深入学习SpringMVC
      • 1、web
      • 2、springmvc-servlet.xml
      • 3、HelloController.java
    • 1.4、使用注解开发SpringMVC
    • 模块
      • 1、web.xml
      • 2、springmvc-servlet.xml
      • 3、HelloController
      • 4、查看Tomcat配置
      • 5、lib中加入所有包
      • 6、结果
  • 三、Controller及RestFul
    • 第一种方法——实现Controller接口
      • springmvc-04-controller模块
        • 1、web
        • 2、springmvc-servlet.xml
        • 3、ControllerTest1
        • 4、test.jsp
        • 5、结果:
    • 第二种——使用注解@Controller
      • 1、ControllerTest2
      • 2、springmvc-servlet.xml
      • 3、结果
    • RestFul 风格
      • RestFulController
      • 结果
      • post方法
  • 四、数据处理及跳转
    • 4.1、结果跳转方式
      • ModelTest1
    • 4.2、数据处理
    • 4.3、乱码问题
      • 问题:
      • 过滤器解决乱码
  • 五、Json交互处理
    • 5.1、Jackson Databind 导入依赖
    • 5.2、解决json乱码问题
      • 方法一
      • 方法二
    • 5.3、返回json字符串统一解决
      • 1、返回多个对象
      • 2、默认时间戳
      • 3、纯java解决—时间戳
      • 4、不使用时间戳的方式
      • 5、工具类
    • 5.4、FastJson
  • 六、SpringMVC:整合SSM
    • 6.1、环境要求:
    • 6.2、创建数据库
    • 6.3、导入依赖
      • 1、pom文件依赖
      • 2、数据库
      • 3、maven静态资源导出问题
    • 6.4、基本架构和配置文件
    • 6.5、Mybatis层
      • 实体类pojo层
      • 接口dao层
      • 业务service层
    • 6.6、Spring层
    • 6.7、SpringMVC层
    • 排错思路
      • 问题:启动不了,工件 ssmbuild:war exploded: 部署工件时出错。请参阅服务器日志了解详细信息。
      • 问题:bean不存在(500)
    • 6.8、查询书籍
    • 6.9、添加书籍
    • 6.10、修改书籍
    • 6.11、删除书籍
    • 6.12、查询书籍
    • 6.13、显示全部书籍
  • 七、Ajax研究
  • 八、拦截器
    • 8.1、拦截器的true与false
      • 首页----登录页面,
      • 拦截器
      • 登录页面登录

一、什么是SpringMVC

SpringMVC01:什么是SpringMVC
假设:你的项目的架构,是设计好的,还是演进的?

  • AlibabaPHP
  • 随着用户大,Java
  • 王坚去IOE
  • MySQL·MySQL:MySQL->AliSQL、
  • AliRedis·All in one->微服务

首先创建项目SpringMVC,导入依赖


<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.0modelVersion>

  <groupId>org.examplegroupId>
  <artifactId>SpringMVCartifactId>
  <version>1.0-SNAPSHOTversion>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.13.2version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.2.0.RELEASEversion>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>2.5version>
    dependency>
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2version>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
  dependencies>

project>

1.1、springmvc-01-serlvet模块

1、模块

【狂神说Java】SpringMVC详细笔记(全)_第1张图片

2、添加Web app的支持!

【狂神说Java】SpringMVC详细笔记(全)_第2张图片
【狂神说Java】SpringMVC详细笔记(全)_第3张图片

3、pom.xml (springmvc-01-serlvet)


<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">
  <parent>
    <artifactId>SpringMVCartifactId>
    <groupId>com.bluegroupId>
    <version>1.0-SNAPSHOTversion>
  parent>
  <modelVersion>4.0.0modelVersion>

  <artifactId>springmvc-01-serlvetartifactId>

  <properties>
    <maven.compiler.source>8maven.compiler.source>
    <maven.compiler.target>8maven.compiler.target>
  properties>

  <dependencies>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>2.5version>
    dependency>
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2version>
    dependency>
  dependencies>

project>

4、HelloServlet

package com.blue.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//实现Servlet接口
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //取得参数
        String method = req.getParameter("method");
        if (method.equals("add")){
            req.getSession().setAttribute("msg","执行了add方法");
        }
        if (method.equals("delete")){
            req.getSession().setAttribute("msg","执行了delete方法");
        }
        //业务逻辑
        //视图跳转
        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

5、test

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    head>
    <body>

      ${msg}

    body>
  html>

6、web


<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-name>helloservlet-name>
    <servlet-class>com.blue.servlet.HelloServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>hellourl-pattern>
  servlet-mapping>

web-app>

7、from

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    head>
    <body>

      <form action="/hello" method="post">
        <input type="text" name="method">
        <input type="submit">
      form>

    body>
  html>

8、结果

【狂神说Java】SpringMVC详细笔记(全)_第4张图片
/hello
【狂神说Java】SpringMVC详细笔记(全)_第5张图片
?method=delete
【狂神说Java】SpringMVC详细笔记(全)_第6张图片

1.2、MVC框架要做哪些事情

  • 将url映射到java类或java类的方法
  • 封装用户提交的数据 .
  • 处理请求–调用相关的业务处理–封装响应数据
  • 将响应的数据进行渲染 . jsp / html 等表示层数据

1.3、文档

4.3.24文档

1.4、注意

如果出现404问题,请查看
【狂神说Java】SpringMVC详细笔记(全)_第7张图片
然后加入所有的包
【狂神说Java】SpringMVC详细笔记(全)_第8张图片
【狂神说Java】SpringMVC详细笔记(全)_第9张图片

二、第一个MVC程序

1.1、springmvc-02-hellomvc

1、模块

【狂神说Java】SpringMVC详细笔记(全)_第10张图片

2、web.xml


<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-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>

  
  
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

3、springmvc-servlet.xml


<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">
    
    
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
    
    
    <bean id="/hello" class="org.example.controller.HelloController"/>

beans>

4、HelloController.java

package org.example.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//注意:这里我们先导入Controller接口
public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
        return mv;
    }
}

5、Configurations配置

配置Tomcat


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
${msg}
body>
html>

如果报错404,就是lib依赖没进去

6、查看Project Structure

【狂神说Java】SpringMVC详细笔记(全)_第11张图片

7、结果

成功!输入/hello
【狂神说Java】SpringMVC详细笔记(全)_第12张图片

1.2、中心控制器

SpringMVC的原理如下图所示:
当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者。
【狂神说Java】SpringMVC详细笔记(全)_第13张图片
HandlerMapping: 处理器映射器
HandlerAdapter: 处理器适配器
viewResolver: 视图解析器
【狂神说Java】SpringMVC详细笔记(全)_第14张图片
图为SpringMVC的一个较完整的流程图,实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者实现。
流程:先申请了一个DispatherServlet,然后访问/hello根据springmvc-servlet.xml中的配置,找到对应的控制器,也就是com.blue.controller.HelloController,然后在对应的控制器类中处理,返回模型,然后根据模型中的跳转,赋值等,在springmvc-servlet.xml中配置的前缀和后缀,跳转到对应的页面
【狂神说Java】SpringMVC详细笔记(全)_第15张图片

1.3、深入学习SpringMVC

DispatcherServlet

1、web


<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-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>

  
  
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

2、springmvc-servlet.xml


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


  
  <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
  
  <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
    
    <property name="prefix" value="/WEB-INF/jsp/"/>
    
    <property name="suffix" value=".jsp"/>
  bean>

  
  <bean id="/hello" class="com.blue.controller.HelloController"/>

beans>

3、HelloController.java

package org.example.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//注意:这里我们先导入Controller接口
public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
        return mv;
    }
}

1.4、使用注解开发SpringMVC

模块

1、web.xml


<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-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>

  
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>


web-app>

2、springmvc-servlet.xml


<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
  http://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">

  
  <context:component-scan base-package="com.blue.controller"/>
  
  <mvc:default-servlet-handler />
  
  <mvc:annotation-driven />

  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    id="internalResourceViewResolver">
    
    <property name="prefix" value="/WEB-INF/jsp/" />
    
    <property name="suffix" value=".jsp" />
  bean>

beans>

3、HelloController

package org.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
    @RequestMapping("/hello")
    public class HelloController {
        //真实访问地址 : 项目名/hello/h1
        @RequestMapping("/h1")
        public String sayHello(Model model){
            //封装数据
            //向模型中添加属性msg与值,可以在JSP页面中取出并渲染
            model.addAttribute("msg","hello,SpringMVCAnnotation!");
            return "hello";   //web-inf/jsp/hello.jsp  会被视图解析器处理:
        }
    }

在视图解析器中我们把所有的视图都存放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。

<%--
   Created by IntelliJ IDEA.
   User: dlmu
   Date: 2022/4/11
   Time: 16:25
   To change this template use File | Settings | File Templates.
 --%>
 
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 
 
     Title
 
 
     ${msg}
 
 

4、查看Tomcat配置

【狂神说Java】SpringMVC详细笔记(全)_第16张图片

5、lib中加入所有包

【狂神说Java】SpringMVC详细笔记(全)_第17张图片

6、结果

image.png

三、Controller及RestFul

第一种方法——实现Controller接口

springmvc-04-controller模块

【狂神说Java】SpringMVC详细笔记(全)_第18张图片

1、web


<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-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

2、springmvc-servlet.xml


<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
  http://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">

  
  
  
  
  

  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  bean>

  <bean name="/t1" class="org.example.controller.ControllerTest1"/>

beans>

3、ControllerTest1

package org.example.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//只要实现了ControlLer 接口的类。说明这就是一个控制器了
public class ControllerTest1 implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","ControllerTest1");
        mv.setViewName("test");
        return mv;
    }
}

4、test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>SpringMVCtitle>
    head>
    <body>
      ${msg}
    body>
  html>

5、结果:

【狂神说Java】SpringMVC详细笔记(全)_第19张图片

第二种——使用注解@Controller

1、ControllerTest2

package org.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller //代表这个类会被spring接管
// 被这个注解的类 中的所有方法,如果返回值是spring,并且有具体的页面可以跳转
// 那么就会被视图解析器解析
public class ControllerTest2 {

    @RequestMapping("/t2")
    public String test1(Model model){
        model.addAttribute("msg","ControllerTest2");
        return "test";
    }
}

2、springmvc-servlet.xml


<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
  http://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">

  
  <context:component-scan base-package="org.example.controller"/>
  
  
  <mvc:annotation-driven />

  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  bean>

beans>

3、结果

正确

RestFul 风格

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
功能
资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应 添加、 删除、修改、查询。
传统方式操作资源 : 通过不同的参数来实现不同的效果!方法单一,post 和 get

http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST

使用RESTful操作资源 : 可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!

http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE

RestFulController

package com.blue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RestFulController {

    //原来的: http://localhost:8080/add?a=1&b=2
    //现在:  http://localhost:8080/add/a/b

    @RequestMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res = a + b;
        model.addAttribute("msg","结果为"+res);
        return "test";
    }

    @RequestMapping("/add")
    public String test2(int a, int b, Model model){
        int res = a + b;
        model.addAttribute("msg","结果为"+res);
        return "test";
    }
}

结果

【狂神说Java】SpringMVC详细笔记(全)_第20张图片

post方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    head>
    <body>
      <form action="/add/1/3" method="post">
        <input type="submit">
      form>

    body>
  html>
package com.blue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RestFulController {

    //原来的: http://localhost:8080/add?a=1&b=2
    //现在:  http://localhost:8080/add/a/b

    //http://localhost:8080/add/a/b
    @RequestMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res = a + b;
        model.addAttribute("msg","结果1为"+res);
        return "test";
    }

    //http://localhost:8080/add/1/3
    @PostMapping("/add/{a}/{b}")
    public String test3(@PathVariable int a,@PathVariable String b, Model model){
        String res = a + b;
        model.addAttribute("msg","结果2为"+res);
        return "test";
    }

}

结果:
【狂神说Java】SpringMVC详细笔记(全)_第21张图片
【狂神说Java】SpringMVC详细笔记(全)_第22张图片

四、数据处理及跳转

4.1、结果跳转方式

ModelAndView

ModelTest1

package com.blue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class ModelTest1 {

    @RequestMapping("m1/t1")	
    public String test1(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
}

【狂神说Java】SpringMVC详细笔记(全)_第23张图片
修改

package com.blue.controller;

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 javax.servlet.http.HttpSession;

@Controller
public class ModelTest1 {

    @RequestMapping("m1/t1")
    public String test1(Model model){
        //转发
        model.addAttribute("msg","ModelTest1");
        return "forward:/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/rsm/t3")
    public String test3(){
        //重定向
        return "redirect:/test.jsp";
    }

}

【狂神说Java】SpringMVC详细笔记(全)_第24张图片

4.2、数据处理

package com.blue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    
    // url: /user/t1?name=xxx  参数一致
    @GetMapping("/t1")
    public String test1(String name, Model model){
        // 1. 接收前端参数
        System.out.println("接收到前端的参数为"+name);

        // 2. 将返回的结果传递纷前端, Model
        model.addAttribute("msg",name);

        // 3. 视图跳转
        return "test";
    }

}

【狂神说Java】SpringMVC详细笔记(全)_第25张图片

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/t1")
    // url: /user/t1?username=xxx  参数不一致
    public String test1(@RequestParam("username") String name, Model model){
        // 1. 接收前端参数
        System.out.println("接收到前端的参数为"+name);

        // 2. 将返回的结果传递纷前端, Model
        model.addAttribute("msg",name);

        // 3. 视图跳转
        return "test";
    }

}

【狂神说Java】SpringMVC详细笔记(全)_第26张图片

/*
1. 接收前端用户传递的参数,判断参数的名字,假设名字直接在方法上,可以直接使用
2. 假设传递的是一个对象User,匹User对象中的字段名:如果名字一致则OK,否则,匹配不到
*/
@GetMapping("/t2")
    public String test2(User user){
    System.out.println(user);
	return "test";
}

【狂神说Java】SpringMVC详细笔记(全)_第27张图片
image.png

4.3、乱码问题

【狂神说Java】SpringMVC详细笔记(全)_第28张图片

问题:

form.jsp

<html>
  <head>
    <title>Titletitle>
  head>
  <body>

    <form action="/e/t1" method="get">
      <input type="text" name="name">
      <input type="submit">
    form>

  body>
html>

EncodingController

package com.blue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class EncodingController {

    @GetMapping("/e/t1")
    public String test1(String name, Model model){
        System.out.println(name);
        model.addAttribute("msg",name);
        return "test";
    }

}

过滤器解决乱码

加上过滤器
EncodingFilter

package com.blue.filter;


import javax.servlet.*;
import java.io.IOException;
import java.util.logging.LogRecord;

public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

web.jsp

<filter>
  <filter-name>encodingfilter-name>
  <filter-class>com.blue.filter.EncodingFilterfilter-class>
filter>
<filter-mapping>
  <filter-name>encodingfilter-name>
  <url-pattern>/*url-pattern>
filter-mapping>

输入http://localhost:8080/form.jsp,输入,点击提交
image.png
【狂神说Java】SpringMVC详细笔记(全)_第29张图片
大佬的过滤器

package com.kuang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 解决get和post请求 全部乱码的过滤器
 */
public class GenericEncodingFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 处理response的字符编码
        HttpServletResponse myResponse = (HttpServletResponse) response;
        myResponse.setContentType("text/html;charset=UTF-8");

        // 转型为与协议相关对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 对request包装增强
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}

// 自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {

    private final HttpServletRequest request;
    // 是否编码的标记
    private boolean hasEncode;

    // 定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
    public MyRequest(HttpServletRequest request) {
        super(request);// super必须写
        this.request = request;
    }

    // 对需要增强方法 进行覆盖
    @Override
    public Map getParameterMap() {
        // 先获得请求方式
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            // post请求
            try {
                // 处理post乱码
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get")) {
            // get请求
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!hasEncode) { // 确保get手动编码逻辑只运行一次
                for (String parameterName : parameterMap.keySet()) {
                    String[] values = parameterMap.get(parameterName);
                    if (values != null) {
                        for (int i = 0; i < values.length; i++) {
                            // 处理get乱码
                            values[i] = new String(values[i]
                                    .getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                        }
                    }
                }
                hasEncode = true;
            }
            return parameterMap;
        }
        return super.getParameterMap();
    }

    // 取一个值
    @Override
    public String getParameter(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
            return null;
        }
        return values[0]; // 取回参数的第一个值
    }

    // 取所有值
    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        return values;
    }
}
}

五、Json交互处理

5.1、Jackson Databind 导入依赖


<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-databindartifactId>
  <version>2.13.1version>
dependency>

springmvc-servlet.xml


<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
  http://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">
    
    
    <context:component-scan base-package="org.example.controller"/>
    
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        
        <property name="suffix" value=".jsp" />
    bean>
    
    

beans>

web.xml


<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-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>

  
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  <filter>
    <filter-name>encodingfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
  filter>

  <filter-mapping>
    <filter-name>encodingfilter-name>
    <url-pattern>/url-pattern>
  filter-mapping>

web-app>

User

package org.example.pojo;


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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

UserController

package org.example.controller;

import org.example.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @RequestMapping("/j1")
    @ResponseBody   //它就不会走视图解析器,会直接返回一个字符串
    public String json1() throws JsonProcessingException {
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("blue1号", 3, "女");
        //将我们的对象解析成为json格式
        String str = mapper.writeValueAsString(user);
        //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
        return str;
    }

}

结果:
【狂神说Java】SpringMVC详细笔记(全)_第30张图片

5.2、解决json乱码问题

方法一

//produces:指定响应体返回类型和编码
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

【狂神说Java】SpringMVC详细笔记(全)_第31张图片

方法二

在springmvc-servlet.xml中添加下面代码

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

【狂神说Java】SpringMVC详细笔记(全)_第32张图片

5.3、返回json字符串统一解决

1、返回多个对象

package com.blue.controller;

import com.blue.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

//@Controller
@RestController //只返回字符串
    public class UserController {

        //produces:指定响应体返回类型和编码
        //    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
        @RequestMapping("/j1")
        //    @ResponseBody   //它就不会走视图解析器,会直接返回一个字符串
        public String json1() throws JsonProcessingException {
            //创建一个jackson的对象映射器,用来解析数据
            ObjectMapper mapper = new ObjectMapper();
            //创建一个对象
            User user = new User("blue1号", 3, "女");
            //将我们的对象解析成为json格式
            String str = mapper.writeValueAsString(user);
            //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
            return str;
        }

        @RequestMapping("/j2")
        public String json2() throws JsonProcessingException {
            //创建一个jackson的对象映射器,用来解析数据
            ObjectMapper mapper = new ObjectMapper();

            List<User> userList = new ArrayList<User>();

            User user1 = new User("blue1", 3, "女");
            User user2 = new User("blue1", 3, "女");
            User user3 = new User("blue1", 3, "女");
            User user4 = new User("blue1", 3, "女");

            userList.add(user1);
            userList.add(user2);
            userList.add(user3);
            userList.add(user4);

            String str = mapper.writeValueAsString(userList);

            return str;
        }

    }

【狂神说Java】SpringMVC详细笔记(全)_第33张图片

2、默认时间戳

@RequestMapping("/j3")
public String json3() throws JsonProcessingException {

	ObjectMapper mapper = new ObjectMapper();
	Date date = new Date();
	return mapper.writeValueAsString(date);
}

【狂神说Java】SpringMVC详细笔记(全)_第34张图片

3、纯java解决—时间戳

@RequestMapping("/j3")
public String json3() throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    Date date = new Date();
    
    // 自定义日期的格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // ObjectMapper,时间解析后的默认格式为:Timestamp,时间戳
    return mapper.writeValueAsString(sdf.format(date));
}

【狂神说Java】SpringMVC详细笔记(全)_第35张图片

4、不使用时间戳的方式

@RequestMapping("/j4")
public String json4() throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    //不使用 时间戳 的方式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(sdf);
    
    Date date = new Date();
    
    // ObjectMapper,时间解析后的默认格式为:Timestamp,时间戳
    return mapper.writeValueAsString(date);
}

【狂神说Java】SpringMVC详细笔记(全)_第36张图片

5、工具类

JsonUtils

package com.blue.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

public class JsonUtils {
    public static String getJson(Object object) {
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        //不使用时间差的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //自定义日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        //指定日期格式
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
@RequestMapping("/j5")
public String json5() throws JsonProcessingException {
    Date date = new Date();
    String json = JsonUtils.getJson(date);
    return json;
}

【狂神说Java】SpringMVC详细笔记(全)_第37张图片

5.4、FastJson

fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。

package com.blue.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class FastJsonDemo {
    public static void main(String[] args) {
        //创建一个对象
        User user1 = new User("秦疆1号", 3, "男");
        User user2 = new User("秦疆2号", 3, "男");
        User user3 = new User("秦疆3号", 3, "男");
        User user4 = new User("秦疆4号", 3, "男");
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        System.out.println("*******Java对象 转 JSON字符串*******");
        String str1 = JSON.toJSONString(list);
        System.out.println("JSON.toJSONString(list)==>"+str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(user1)==>"+str2);

        System.out.println("\n****** JSON字符串 转 Java对象*******");
        User jp_user1=JSON.parseObject(str2,User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

        System.out.println("\n****** Java对象 转 JSON对象 ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

        System.out.println("\n****** JSON对象 转 Java对象 ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
    }
}	
@RequestMapping("/j6")
public String json6() throws JsonProcessingException {

    List<User> userList = new ArrayList<User>();

    User user1 = new User("blue1", 3, "女");
    User user2 = new User("blue1", 3, "女");
    User user3 = new User("blue1", 3, "女");
    User user4 = new User("blue1", 3, "女");
    
    userList.add(user1);
    userList.add(user2);
    userList.add(user3);
    userList.add(user4);
    
    String str = JSON.toJSONString(userList);
    return str;
	}
}

【狂神说Java】SpringMVC详细笔记(全)_第38张图片

六、SpringMVC:整合SSM

6.1、环境要求:

  • IDEA
  • MySQL 5.7.19(我用的8.0+)
  • Tomcat 9
  • Maven 3.6

要求:
需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;

6.2、创建数据库

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
   `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
   `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
   `bookCounts` INT(11) NOT NULL COMMENT '数量',
   `detail` VARCHAR(200) NOT NULL COMMENT '描述',
   KEY `bookID` (`bookID`)
 ) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

6.3、导入依赖

新建项目,导入依赖junit、mysql、c3p0、servlet、JSP 、Mybatis、Spring,连接数据库

1、pom文件依赖

<dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        dependency>
        
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.0.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
        dependency>
    dependencies>

2、数据库

【狂神说Java】SpringMVC详细笔记(全)_第39张图片

3、maven静态资源导出问题

<build>
  <resources>
    <resource>
      <directory>src/main/javadirectory>
      <includes>
        <include>**/*.propertiesinclude>
        <include>**/*.xmlinclude>
      includes>
      <filtering>falsefiltering>
    resource>
    <resource>
      <directory>src/main/resourcesdirectory>
      <includes>
        <include>**/*.propertiesinclude>
        <include>**/*.xmlinclude>
      includes>
      <filtering>falsefiltering>
    resource>
  resources>
build>

6.4、基本架构和配置文件

建立包结构

  • com.kuang.pojo
  • com.kuang.dao
  • com.kuang.service
  • com.kuang.controller

配置文件

  • mybatis-config.xml
  • applicationContext.xml
  • database.properties

mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="com.kuang.pojo"/>
    typeAliases>
    
configuration>

applicationContext.xml


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

database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

6.5、Mybatis层

实体类pojo层

字段和数据库内的一样

package com.kuang.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;

}

【狂神说Java】SpringMVC详细笔记(全)_第40张图片

接口dao层

BookMapper

package com.kuang.dao;

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

import java.util.List;

public interface BookMapper {

    // 增加一本书
    int addBook(Books books);

    // 删除一本书,booId和id不一样,所以用个注解转换
    int deleteBookById(@Param("bookId") int id);

    //更新一本书
    int updateBook(Books books);

    // 查询一本书
    Books queryBookById(@Param("bookId") int id);

    // 查询全部的书
    List<Books> queryAllBook();

}

BookMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.dao.BookMapper">
    
    
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName,bookCounts,detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    insert>
    
    
    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.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">
        select * from ssmbuild.books
        where bookID = #{bookID}
    select>
    
    
    <select id="queryAllBook" resultType="Books">
        SELECT * from ssmbuild.books
    select>

mapper>

mybatis-config.xml
接口和mapper写完了,就要绑定到xml中


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    
    <typeAliases>
        <package name="com.kuang.pojo"/>
    typeAliases>
    
    <mappers>
        <mapper class="com.kuang.dao.BookMapper"/>
    mappers>

configuration>

业务service层

BookService

package com.kuang.service;


import com.kuang.pojo.Books;

import java.util.List;

public interface BookService {

    // 增加一本书
    int addBook(Books books);

    // 删除一本书,不是dao层,所以不用加注解@Para("bookId")
    int deleteBookById(int id);

    //更新一本书
    int updateBook(Books books);

    // 查询一本书
    Books queryBookById(int id);

    // 查询全部的书
    List<Books> queryAllBook();

}

BookServiceImpl

package com.kuang.service;


import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService{

    // service调 dao层:组合Dao
    private BookMapper bookMapper;

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

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

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

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

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

    @Override
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

6.6、Spring层

spring-dao.xml
将这个上下午配置到之前applicationContext.xml的上下文


<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="classpath:database.properties"/>
    
    
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        
        
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        
        <property name="autoCommitOnClose" value="false"/>
        
        <property name="checkoutTimeout" value="10000"/>
        
        <property name="acquireRetryAttempts" value="2"/>
    bean>
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>
    
    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.kuang.dao"/>
    bean>

beans>

spring-service.xml


<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
  http://www.springframework.org/schema/context/spring-context.xsd">
    
    
    <context:component-scan base-package="com.kuang.service" />
    
    
    <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    bean>
    
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource" />
    bean>

beans>

若配置的上下文没有自动整合,可以手动导入


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

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
beans>

6.7、SpringMVC层

增加web框架支持!
web.xml


<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-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      
      <param-value>classpath:applicationContext.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  
  <filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>
      org.springframework.web.filter.CharacterEncodingFilter
    filter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <session-config>
    <session-timeout>15session-timeout>
  session-config>

web-app>

spring-mvc.xml


<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
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/mvc
  https://www.springframework.org/schema/mvc/spring-mvc.xsd">

  
  
  <mvc:annotation-driven />
  
  <mvc:default-servlet-handler/>

  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  bean>

  
  <context:component-scan base-package="com.kuang.controller" />

beans>

BookController

package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.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.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }
}

allBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>书籍展示title>
    head>
    <body>
      <h1>书籍展示h1>
    body>
  html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>首页title>
head>
<body>

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

body>
html>

排错思路

问题:启动不了,工件 ssmbuild:war exploded: 部署工件时出错。请参阅服务器日志了解详细信息。

wen-inf下建立 lib,中加maven静态资源
【狂神说Java】SpringMVC详细笔记(全)_第41张图片

问题:bean不存在(500)

步骤:
1、查看这个bean注入是否成功!
2、Junit单元测试,看我们的代码是否能够查询出来结果!

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookServiceImpl = (BookService) context.getBean("BookServiceImpl");

        for (Books books:bookServiceImpl.queryAllBook()){
            System.out.println(books);
        }

    }
}

3、问题,一定不在我们的底层,是spring出了问题!
4、SpringMVC,整合的时候没调用到我们的service.层的bean

  • applicationContext.xml没有注入bean
  • web.xml中,我们也绑定过配置文件!发现问题,我们配置的是Spring-mvc.Xml这里面确实没有service bean,所以报空指针
  • 所以,在web.xml中classpath:applicationContext.xml而不是classpath:spring-mvc.xml

6.8、查询书籍

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>首页title>
      <style>
        a{
          text-decoration: none;
          color: blue;
          font-size: 18px;
        }
        h3{
          width: 180px;
          height: 38px;
          margin: 100px auto;
          text-align: center;
          line-height: 38px;
          background: deepskyblue;
          border-radius: 5px;
        }
      style>

    head>
    <body>

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

    body>
  html>

查找BootStrap CDN,搜索



<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">



<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js">script>



<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js">script>

allbook.jsp

  • 先导入<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>,放第一行
<%@ 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">

        

        <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js">script>

        

        <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js">script>
      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 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')}">--%>
                      <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>
                        tr>
                      c:forEach>
                    tbody>
                    table>
                    div>
                    div>


                    div>



                    body>
                    html>

【狂神说Java】SpringMVC详细笔记(全)_第42张图片

6.9、添加书籍

allBook.jsp

<div class="row">
  <div class="col-md-4 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍a>
  div>
div>

BookController.java

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

// 添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
    System.out.println("addBook=>"+books);
    bookService.addBook(books);
    return "redirect:/book/allBook";
}

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>

        <%--  BootStrap美化界面  --%>
          <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-header">
                <h1>
                  <small>新增书籍small>
                h1>
              div>
            div>
          div>

          <form action="${pageContext.request.contextPath}/book/addBook" 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>

结果
【狂神说Java】SpringMVC详细笔记(全)_第43张图片
【狂神说Java】SpringMVC详细笔记(全)_第44张图片

6.10、修改书籍

allBook.jsp

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

      td>
    tr>
  c:forEach>
tbody>

BookController.java

//修改书籍
@RequestMapping("/updateBook")
public String updateBook( Books books) {
    System.out.println("updateBook=>"+books);
    int i =bookService.updateBook(books);
    if (i > 0) {
        System.out.println("添加books成功"+books);
    }
    return "redirect:/book/allBook";
}

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">
    
    <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/" method="post">
        <div class="form-group">
            <label>书籍名称label>
            <input type="text" name="bookName" class="form-control" value="${QBook.bookName}" required>
        div>
        <div class="form-group">
            <label>书籍数量label>
            <input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
        div>
        <div class="form-group">
            <label>书籍描述label>
            <input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
        div>
        <div class="form-group">
            <input type="submit" class="form-control" value="修改">
        div>
        <%--        <input type="submit" value="提交"/>--%>
    form>

div>

结果
【狂神说Java】SpringMVC详细笔记(全)_第45张图片

BookController

@RequestMapping("/updateBook")
public String updateBook( Books books) {
    System.out.println("updateBook=>"+books);
    bookService.updateBook(books);
    return "redirect:/book/allBook";
}

BookServiceImpl

@Override
    public int updateBook(Books books) {
        System.out.println("BookServiceImpl:updateBook=>"+books);
return bookMapper.updateBook(books);
}

导入jar包

<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.4version>
dependency>

加上事务
spring-service.xml


<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
  http://www.springframework.org/schema/beans/spring-beans.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
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd">

  
  <context:component-scan base-package="com.kuang.service" />

  
  <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
    <property name="bookMapper" ref="bookMapper"/>
  bean>

  
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    
    <property name="dataSource" ref="dataSource" />
  bean>

  
  
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="*" propagation="REQUIRED"/>
    tx:attributes>
  tx:advice>

  
  <aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.kuang.dao.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
  aop:config>

beans>

lib包导入
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">
        
        <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>

          <%--  出现的问题:我们提交了修改的SQ请求,但是修改失败,初次考虑,是事务问题,配置完华事务,依旧失败!--%>
            <%-- 看一下SQL语句,能否执行成功:SQL执行失败,修政未完成-%>  %>--%>
              <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
                <input type="hidden" name="bookID" value="${QBook.bookID}">
                <div class="form-group">
                  <label>书籍名称label>
                  <input type="text" name="bookName" class="form-control" value="${QBook.bookName}" required>
                div>
                <div class="form-group">
                  <label>书籍数量label>
                  <input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
                div>
                <div class="form-group">
                  <label>书籍描述label>
                  <input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
                div>
                <div class="form-group">
                  <input type="submit" class="form-control" value="修改">
                div>
                <%--        <input type="submit" value="提交"/>--%>
              form>

            div>

手动添加日志
mybatis-config.xml
【狂神说Java】SpringMVC详细笔记(全)_第46张图片

6.11、删除书籍

//删除书籍
@RequestMapping("/deleteBook")
    public String deleteBook(int id){
    bookService.deleteBookById(id);
    return "redirect:/book/allBook";
}

allBook.jsp

<td>
  <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">修改a> |
  <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除a>
td>

6.12、查询书籍

BookMapper

Books queryBookByName(String bookName);

BookMapper.xml

<select id="queryBookByName" resultType="Books">
  select * from ssmbuild.books where bookName = #{bookName}
select>

BookService

Books queryBookByName(String bookName);

BookServiceImpl

@Override
public Books queryBookByName(String bookName) {
    return bookMapper.queryBookByName(bookName);
}

BookController

//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
    Books books = bookService.queryBookByName(queryBookName);
    System.err.println("books=>"+books);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    model.addAttribute("list",list);
    return "allBook";
}

addBook.jsp

<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">
    <%-- 查询书籍--%>
      <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
        <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询书籍的名称">
        <input type="submit" value="查询" class="btn btn-primary">
      form>
  div>
div>

结果
【狂神说Java】SpringMVC详细笔记(全)_第47张图片
报500错误,dao.BookMapper.xml查不到
加上maven资源过滤

<build>
  <resources>
    <resource>
      <directory>src/main/javadirectory>
      <includes>
        <include>**/*.propertiesinclude>
        <include>**/*.xmlinclude>
      includes>
      <filtering>falsefiltering>
    resource>
    <resource>
      <directory>src/main/resourcesdirectory>
      <includes>
        <include>**/*.propertiesinclude>
        <include>**/*.xmlinclude>
      includes>
      <filtering>falsefiltering>
    resource>
  resources>
build>

6.13、显示全部书籍

allBook.jsp

<div class="row">
  <div class="col-md-4 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍a>
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍a>
  div>
  <div class="col-md-8 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>

BookController

//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
    Books books = bookService.queryBookByName(queryBookName);
    System.err.println("books=>"+books);
    List<Books> list = new ArrayList<Books>();
    list.add(books);

    if (books == null){
        list = bookService.queryAllBook();
        model.addAttribute("error","未查到");
    }

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

结果
【狂神说Java】SpringMVC详细笔记(全)_第48张图片

七、Ajax研究

模块
image.png
web.xml


<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-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:applicationContext.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>

  
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  <filter>
    <filter-name>encodingfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
  filter>

  <filter-mapping>
    <filter-name>encodingfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

web-app>

applicationContext.xml


<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
  http://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">

  
  <context:component-scan base-package="com.blue.controller"/>
  
  <mvc:default-servlet-handler />
  <mvc:annotation-driven/>
  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    id="internalResourceViewResolver">
    
    <property name="prefix" value="/WEB-INF/jsp/" />
    
    <property name="suffix" value=".jsp" />
  bean>

  

beans>

AjaxController

package com.blue.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AjaxController {
    @RequestMapping("/t1")
    public String test(){
        return "hello";
    }
}

结果:
【狂神说Java】SpringMVC详细笔记(全)_第49张图片
页面无刷新效果
【狂神说Java】SpringMVC详细笔记(全)_第50张图片
test.html

DOCTYPE html>
<html lang="en">
  <head>
    <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="https://www.bilibili.com/">
        <input type="button" value="提交" onclick="go()">
      p>
    div>

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

  body>
html>

image.png
因为没用到,所以博主没看完,抱歉(。・_・。)ノI’m sorry~

八、拦截器

8.1、拦截器的true与false

模块
【狂神说Java】SpringMVC详细笔记(全)_第51张图片
拷过来
【狂神说Java】SpringMVC详细笔记(全)_第52张图片
main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    head>
    <body>
      <h1>首页h1>
    body>
  html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    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>

TestController

package com.blue.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/t1")
    public String test(){
        System.out.println("TestController==> test()执行了");
        return "OK";
    }
}

HandlerInterceptor

package com.blue.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("================处理前===============");
        return true;
        //        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("================处理后===============");
        //        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

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

applicationContext.xml


<mvc:interceptors>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.blue.config.MyInterceptor"/>
  mvc:interceptor>
mvc:interceptors>

结果:【狂神说Java】SpringMVC详细笔记(全)_第53张图片
拦截器为false

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("================处理前===============");
        return false;
        //        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

结果
【狂神说Java】SpringMVC详细笔记(全)_第54张图片
【狂神说Java】SpringMVC详细笔记(全)_第55张图片

首页----登录页面,

LoginController

package com.blue.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {
    //跳转到登陆页面
    @RequestMapping("/jumplogin")
    public String jumpLogin() throws Exception {
        return "login";
    }

    //跳转到成功页面
    @RequestMapping("/jumpSuccess")
    public String jumpSuccess() throws Exception {
        return "success";
    }

    //登陆提交
    @RequestMapping("/login")
    public String login(HttpSession session, String username, String pwd) throws Exception {
        // 向session记录用户身份信息
        System.out.println("接收前端==="+username);
        session.setAttribute("user", username);
        return "success";
    }

    //退出登陆
    @RequestMapping("logout")
    public String logout(HttpSession session) throws Exception {
        // session 过期
        session.invalidate();
        return "login";
    }
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: dlmu
  Date: 2022/4/23
  Time: 9:59
  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><a href="${pageContext.request.contextPath}/goLogin">a>h1>
        <h1><a href="${pageContext.request.contextPath}/main">a>h1>
      body>
    html>

拦截器

LoginInterceptor

package com.blue.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        // 如果是登陆页面则放行
        //        System.out.println("uri: " + request.getRequestURI());
        if (request.getRequestURI().contains("goLogin")) {
            return true;
        }

        HttpSession session = request.getSession();

        // 如果用户已登陆也放行
        if(session.getAttribute("user") != null) {
            return true;
        }

        // 用户没有登陆跳转到登陆页面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

applicationContext.xml


<mvc:interceptors>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.blue.config.MyInterceptor"/>
  mvc:interceptor>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.blue.config.LoginInterceptor"/>
  mvc:interceptor>
mvc:interceptors>

登录页面登录

LoginInterceptor

package com.blue.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        // 如果是登陆页面则放行
        if (request.getRequestURI().contains("goLogin")) {
            return true;
        }
        if (request.getRequestURI().contains("login")) {
            return true;
        }

        HttpSession session = request.getSession();

        // 如果用户已登陆也放行 第一次登录,也是没有session的:
        if(session.getAttribute("userLoginInfo") != null) {
            return true;
        }

        // 用户没有登陆跳转到登陆页面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

LoginController

package com.blue.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

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

    //登陆提交
    @RequestMapping("/login")
    public String login(HttpSession session, String username, String pwd, Model model){
        // 向session记录用户身份信息
        System.out.println("接收前端login==="+username);
        session.setAttribute("userLoginInfo", username);
        model.addAttribute("username",username);
        return "main";
    }

    //退出登陆
    @RequestMapping("/goOut")
    public String logout(HttpSession session){
        // session 过期
        //        session.invalidate();
        session.removeAttribute("userLoginInfo");
        return "main";

    }
}                                                                                                                             43

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Titletitle>
    head>
    <body>
      <h1>首页h1>

      <span>${username}span>

      <p>
        <a href="${pageContext.request.contextPath}/user/goOut">注销a>
      p>
    body>
  html>

【狂神说Java】SpringMVC详细笔记(全)_第56张图片
【狂神说Java】SpringMVC详细笔记(全)_第57张图片

你可能感兴趣的:(舔砖加瓦(Java),java,servlet,spring)