小言_互联网的博客

81.【SpringMVC】

503人阅读  评论(0)

SpringMVC

(一)、认识MVC三层架构

https://springref.com/
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc%20Spring%20MVC

1.回顾MVC

SpringMVC 控制器默认支持GET和POST两种方式,默认的是转发,而不是重定向。WEB-INF目录下的文件只能通过请求转发进行获取,重定向不能进行获取。

(1).什么是MVC三层框架

经典MVC模式中,M是指业务模型(Model–dao service),V是指用户界面(View – jsp),C则是控制器(Control–servlet),使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。其中,View的定义比较清晰,就是用户界面。

(2).MVC要做那些事情?

  1. 将URL 映射到java类或java方法上
  2. 封装用户提交的数据
  3. 处理请求:调用相关的业务处理–封装响应数据
  4. 将相应的数据进行渲染 .jsp等表示层数据

(3).常见的MVC三层框架结构

常见的服务端MVC框架:Struts,SpringMvc,ASP
常见的前端MVC框架: VUE React

(4).知识拓展

  1. 全栈 : 后台+前端+数据库+运维
  2. 前端 : 后台+前端

2.代码回顾

依赖

    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

<!--        servlet-jsp依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
        </dependency>

<!--        jstl依赖-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
            <scope>provided</scope>
        </dependency>

<!--        standard依赖-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
<!--        junit 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
<!--     基本框架   -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.19.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

 

servlet层

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

public class HelloServlet extends HttpServlet {
   
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
//        1.获取前端的参数
        String method=req.getParameter("method");
//        2.进行判断要执行哪一个?
        if (method != null&&method.equals("add")) {
   
            req.getSession().setAttribute("msg","执行了add方法");
        }if (method != null&&method.equals("delete")) {
   
            req.getSession().setAttribute("msg","执行了delete方法");
        }
        req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
    }

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


 

配置web.xml映射

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>test1</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>test1</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

在WEB-INF下创建jsp文件夹创建test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 22612
  Date: 2022/12/24
  Time: 10:28
  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>跳转成功了呀</h1>
${
   msg}
</body>
</html>


 

首页设置

<%--
  Created by IntelliJ IDEA.
  User: 22612
  Date: 2022/12/24
  Time: 10:19
  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>首页面加载中</h1>
<form action="hello" method="post">
  <input type="text" name="method">
  <button type="submit"></button>
</form>
  </body>
</html>


 

3.什么是SpringMVC

SpringMVC是Spring Framework的一部分,是基于java实现的MVC的轻量级Web框架

  1. 轻量级,简单易学
  2. 高效,基于请求相应的MVC框架
  3. 与Spring兼容性好,无缝结合
  4. 约定优于配置
  5. 功能强大: RESTful、数据验证、格式化、本地化、主题等
  6. 简介灵活

(二)、第一个SpringMVC

0.前提

不要导入: servlet jsp jstl 的这三个jar包到lib目录下,但是要存在于pom.xml里,否则会出现严重的500错误。切记。其他的依赖需要导入lib目录下


1.搭建环境

    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

<!--        servlet-jsp依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
        </dependency>

<!--        jstl依赖-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
            <scope>provided</scope>
        </dependency>

<!--        standard依赖-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
<!--        junit 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
<!--     基本框架   -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.19.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

 

2.配置WEB-INF的XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

  <servlet>

    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

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

</web-app>


 

3.在资源Resource的包下设置springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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"/>

    <!--  视图解析器: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>
    <bean id="/hello" class="com.Jsxs.controller.helloController"/>
</beans>


 

4.在WEB-INF的包下进行创建jsp/hello.jsp

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

${
   msg}

</body>
</html>

5.配置控制层的实现

package com.Jsxs.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中
        mv.addObject("msg","HelloSpringMVC");
        mv.setViewName("hello");
        return mv;
    }
}

 

6.注意如果出现404和500的错误

  1. 首先把继承的包导入到对应的空间中的lib目录中去

  1. 如果出现500的错误,显示不能创建bean或者什么什么的,这边建议直接另起一个项目,重新建立一个已经配置的web文件。(就是模板)

3.可以不创建新的web模板,我们只需要在创建Model的时候,我们应该对lib目录下进行添加如下几个内容,不能多。

(三)、SpringMVC执行原理

1.中心控制器:

SpringMVC的web框架围绕DispatcherServlet设计,DispatcherServlet的作用就是将请求分发到不同的处理器、从spring2.5开始,用户可以采用基于注解的controller声明方式。

2.原理解析(左边部分不用我们操作)

(1).DispatcherServlet

DispatcherServlet表示前置控制器,是整个SpringMVC的控制核心用户发出请求,DispatcherServlet接受请求并拦截请求。(映射就是)

  • 我们假设请求的url为:
  • http://localhost:80/SpringMVC_03_Hello_war/hello
  • 如上的url可以分为三部分
  • http://http://localhost:80 - - - 服务器域名
  • SpringMVC_03_Hello_war - - - 部署在服务器上的web站点
  • hello - - - - 表示控制器
  • 通过分析,如上url表示为 : 请求位于服务器 localhost:80 上的 SpringMVC_03_Hello_war站点的hello控制器

(2).HandlerMapping

HandlerMapping为处理器映射,DispatcherServlet调用HandlerMapping,HandlerMapping根据url查找 Handler

(3).HandlerExpecution

HandlerExpecution表示具体的Handler,其主要作用是根据url查找控制器,如url被查找控制为 : hello

【4】.返回给DispatcherServlet

HandlerExpecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等

(5).HandlerAdpate

HandlerAdpate表示处理适配器,其按照特定的规则去执行Handler

(6).Handler让具体的Controller执行

(7).Controller将拘役的执行信息返回给HandlerAdpate,如Model和View

【8】.HandlerAdpter将试图逻辑名或模型传递给DispatcherServlet.

(9).DispatcherServlet调用视图解析器(VierResolver)来解析HandlerAdpater传递的逻辑视图名

视图解析器的作用:
1.获取Model和view的数据
2.解析model和view的视图名字
3.拼接试图的名字,找到具体的视图

(10).视图解析器将解析的逻辑视图传给DispatcherServlet

(11).DispatcherServlet根据视图解析器解析视图的结果,调用器具图的视图。

(12).最终视图呈现给用户

(四)、深入了解SpringMVC

(1).在web.xml配置DispatcherServlet 核心

1.配置DispatcherServlet 核心
 <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
2.配置DispatcherServlet 映射
 <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
3.绑定spring文件    
 <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
 </init-param>
 4.启动级别: 就是让他和服务器进行同步
<load-on-startup>1</load-on-startup>

 
<?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">
<!--  1.  配置DispatcherServlet 核心-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--  3.      DispatcherServlet要绑定Spring的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
<!--   4.     启动级别: 就是让他和服务器进行同步-->
        <load-on-startup>1</load-on-startup>
    </servlet>
<!--  2.
    在SpringMVC中,
    / 只匹配所有的请求,不会去请求jsp
    /* 匹配所有的请求,会请求jsp
    在springMvc中 我们尽量写/
-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

(2).配置Spring文件

1.配置处理器映射器
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
2.配置处理器适配器
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
3.配置视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--   前缀     -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
<!--   后缀     -->
        <property name="suffix" value=".jsp"/>
</bean>
4.配置bean
<bean id="/test" class="com.Jsxs.controller.helloController"/>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 处理器映射器:  (BNUHM)  对应图 【2-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 处理器适配器    对应 图 【5-->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

<!-- 视图解析器   对应 图 【9-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--   前缀     -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
<!--   后缀     -->
        <property name="suffix" value=".jsp"/>
    </bean>
<!--  因为处理器映射器需要借助一个bean , 所以我们应该配置一个bean-->
    <bean id="/test" class="com.Jsxs.controller.helloController"/>
</beans>

 

(3).配置控制层(Controller)

1.继承接口Controller接口,重写处理请求的方法

2.创建ModelAndView
 ModelAndView modelAndView = new ModelAndView();
3.ModelAndView进行添加业务需求
modelAndView.addObject("msg",result);
4.进行视图的跳转
 modelAndView.setViewName("test");
5.返回视图
package com.Jsxs.controller;

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

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

//  对应 图 【6】
public class helloController implements Controller {
   
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
   
//       创建ModelAndView
        ModelAndView modelAndView = new ModelAndView();
//        业务代码
        String result="你好啊 小明";

       modelAndView.addObject("msg",result);
//       视图进行跳转
        modelAndView.setViewName("test");
        return modelAndView;
    }
}

 

(五)、使用注解开发SpringMVC

(1).使用SpringMVC必须要配置的三大件:
处理器映射器 处理器适配器 视图解析器
(2).如果使用注解进行开发的话
那么 处理器映射器 处理器适配器 就会被自动注入,不用我们去配置了

1.Spring下面的配置(可以写死)

1.进行配置的约束
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
2.扫描注解下面的所有包
<context:component-scan base-package="Com.Jsxs.Controller"/>
3.使SpringMVC处理静态资源
 <mvc:default-servlet-handler/>
4.导入驱动的注解
<mvc:annotation-driven/>
5.视图解析器
<?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
       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.Jsxs.Controller"/>
<!--    让Spring MVC不处理静态资源-->
    <mvc:default-servlet-handler/>
<!--    支持驱动注解
    在spring中一般采用 @RequestMapping注解来完成映射关系
    要想使 @RequestMapping 注解生效
    必须像上下文中注册DefaultAnnotationHandleMapping
    和一个AnnotationMethodHandlerAdapter实列
    这两个实列分别在类级别和方法级别处理
    而annotation-driven配置,自动帮我们完成上述的两个实列的注入
-->
    <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>

 

2.注册DispatcherServlet(可以写死 )

<?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">
    <!--  1.  配置DispatcherServlet 核心-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--  3.      DispatcherServlet要绑定Spring的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--   4.     启动级别: 就是让他和服务器进行同步-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--  2.
        在SpringMVC中,
        / 只匹配所有的请求,不会去请求jsp
        /* 匹配所有的请求,会请求jsp
        在springMvc中 我们尽量写/
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

3.Controller控制层

1.@Controller 设置为 controller
2. @RequestMapping("/hello") 请求映射
package Com.Jsxs.Controller;

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

@Controller
public class HelloController {
   
    @RequestMapping("/hello")
    public String hello(Model model){
   
        model.addAttribute("msg","hello springAnnotation!!");
        return "hello";   //会被试图解析器处理;
    }
}


@RequestMapping(“/hello”)才是真正的映射的地址

(六)、Controller【控制器】

  • 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现
  • 在控制器负责解析用户的请求并将其转换成一个模型
  • 在Spring MVC中一个控制器类可以包含多个方法
  • 在Spring MVC中,对于Controller的配置有很多种

1.实现一个Controller的接口

控制层

package Com.Jsxs.Controller;

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

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

public class controllerFirst implements Controller {
   
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
   
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg","这是通过接口来实现");
        modelAndView.setViewName("hello");
        return modelAndView;
    }
}

 

spring层

<?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
       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.Jsxs.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>
    
<bean class="Com.Jsxs.Controller.controllerFirst" id="/hello"/>

</beans>

 

2.使用注解实现Controller

@Component  组件
@service  service
@Controller controller
@Repository dao
1.这个返回类型为字符串的方法,返回值的名字不是随便要起的,而是存在页面的
名字。如果乱其名字的话,我们可能会面临404的尴尬处境
2.方法里面的参数是 Model 不是其他的

控制层

package Com.Jsxs.Controller;

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

@Controller
public class TwoController {
   

    @RequestMapping("/hello2")
    public String test(Model model){
   
        model.addAttribute("msg","这是利用注解进行开发的数据");
        return "hello";  //这个的意思就是说要和jsp文中的文件的名字一样,不能乱起名字
    }
}

spring可以不用写bean了

<?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
       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.Jsxs.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.新思路

并不是说一个网站又N张页面,我们就对它设置了N张的JSP,而有可能我们只是对其进行了一些的数据更新,并没有做到每一个数据更新就需要更换一张JSP
eg:

package Com.Jsxs.Controller;

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

@Controller
public class TwoController {
   

    @RequestMapping("/hello2")
    public String test(Model model){
   
        model.addAttribute("msg","这是利用注解进行开发的数据2");
        return "hello";  //这个的意思就是说要和jsp文中的文件的名字一样,不能乱起名字
    }
    @RequestMapping("/hello1")
    public String test2(Model model){
   
        model.addAttribute("msg","这是利用注解进行开发的数据1");
        return "hello";  //这个的意思就是说要和jsp文中的文件的名字一样,不能乱起名字
    }
}


 

(七)、RequestMapping【请求映射】

@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上

1.RequestMapping在方法上

RequestMapping在方法上会精确的找到这一 个方法

package Com.Jsxs.Controller;

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

@Controller
public class Controller2 {
   

    @RequestMapping("/hello2")
    public String test(Model model){
   
        model.addAttribute("msg","进入了控制层2,映射是hello2");
        return "hello";  //这个的意思就是说要和jsp文中的文件的名字一样,不能乱起名字
    }
    @RequestMapping("/hello1")
    public String test2(Model model){
   
        model.addAttribute("msg","进入了控制层2,映射是hello1");
        return "hello";  //这个的意思就是说要和jsp文中的文件的名字一样,不能乱起名字
    }
}

 

2.RequestMapping在类上

package Com.Jsxs.Controller;

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

@Controller
@RequestMapping("/hello3")
public class Controller3 {
   
@RequestMapping("/hello2")
    public String test(Model model){
   
        model.addAttribute("msg","进入了控制层3,映射的IP是hello3");
        return "hello";
    }
}


 

3.RequestMapping在类上和方法上同时存在

我们要先访问类路径上的然后再访问方法路上的,相当于加了一层
http://localhost/SpringMVC_06_Controller_war_exploded/hello3/hello2
package Com.Jsxs.Controller;

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

@Controller
@RequestMapping("/hello3")
public class Controller3 {
   
    @RequestMapping("hello2")
    public String test(Model model){
   
        model.addAttribute("msg","进入了控制层3,映射的IP是hello3");
        return "hello";
    }
}

(八)、RestFul 风格【路径】

1.Restful 概念

Restful 一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。就是用于一个资源的定位操作。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

2.RestFul 功能

  • 资源: 互联网所有事务都可以被认为是抽象资源
  • 资源操作: 使用 POST、DELETE、PUT、GET
  • 分别对应着增删改查

3.传统方式操作资源

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 删除 GETPOST

4.使用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 

(1).后端挖空前端怎么输入【旧的】

package Com.Jsxs.Controller;

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

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
    @RequestMapping("/add")
    public String test(int a, int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为:"+result);
        return "hello";
    }
}

 

http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2

(2).后端挖空(路径)前端怎么输入【RestFul风格】

1.添加注解: @PathVariable 
2.(@PathVariable int a, @PathVariable int b, Model model)
package Com.Jsxs.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 Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为:"+result);
        return "hello";
    }
}

 

(3).RequestMethod.DELETE方式进行获取【1】

SpringMVC 控制器默认支持GET和POST两种方式

package Com.Jsxs.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;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
    @RequestMapping(name = "/add/{a}/{b}",method = RequestMethod.DELETE)
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为:"+result);
        return "hello";
    }
}

 


指定为RequestMethod.GET进行获取

package Com.Jsxs.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;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为:"+result);
        return "hello";
    }
}

 

(4).利用注解提交的方式【2】

package Com.Jsxs.Controller;

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

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
//    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
    @GetMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为:"+result);
        return "hello";
    }
}

 

(5).四种注解的提交方式

    @GetMapping("/add/{a}/{b}")   get方式进行提交
    @PostMapping("/add/{a}/{b}")   post方式进行提交
    @DeleteMapping("/add/{a}/{b}")  delete方式进行提交
    @PutMapping("/add/{a}/{b}")  put方式进行提交

(6).访问地址相同,但是提交方式不同

实质: 就是提交的方式不同,所以在路径相同的情况下访问的内容不同

首先创建一个a.jsp


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

创建一个类,类中有两个方法分别对应着不同的调用方式

package Com.Jsxs.Controller;

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

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add/1/2
    @GetMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为get1:"+result);
        return "hello";
    }
//    http://localhost/SpringMVC_06_Controller_war_exploded/add/1/2
    @PostMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为post2:"+result);
        return "hello";
    }
}

 

通过请求转发,也就是方法一默认的GET方式提交>

通过表单进行提交,提交方式为post,提交的位置是方法2利用post提交

(7).访问地址相同,提交方式也相同

package Com.Jsxs.Controller;

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

@Controller
public class Controller4 {
   
//    http://localhost/SpringMVC_06_Controller_war_exploded/add?a=1&b=2
//    原来的方式,前端如何给后端赋值?  路径?a=变量1&b=变量2
//    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)

//    http://localhost/SpringMVC_06_Controller_war_exploded/add/1/2
    @GetMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为get1:"+result);
        return "hello";
    }
//    http://localhost/SpringMVC_06_Controller_war_exploded/add/1/2
    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable int b, Model model){
   
        int result=a+b;
        model.addAttribute("msg","结果为post2:"+result);
        return "hello";
    }
}

 

(九)、ModelAndView (视图解析器)

设置ModelAndView对象,根据View的名称和视图解析器跳到指定的页面;
页面: {视图解析器前缀}+viewName+{视图解析器后缀}

1.跟据视图解析器进行转发的两种形式

(1).利用Servlet进行跳转

package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "hello";
    }
}

 

(2).利用Model进行跳转

package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(Model model){
   
        model.addAttribute("msg","通过Model进行视图的跳转");
        return "hello";
    }
}

 

(3).路径映射的问题怎么解决

因为在JSP中我们不能使用绝对路径,所以我们要使用EL表达式进行干涉


如何干涉? ${pageContext.request.contextPath}/login.do

2.没有视图解析器的转发方式

(1).全限定名进行转发

Spring

<?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
       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.Jsxs.Controller"/>
<!--    设置默认-->
    <mvc:default-servlet-handler/>
<!--    设置驱动器-->
    <mvc:annotation-driven/>
</beans>

 

控制层

return "/WEB-INF/jsp/hello.jsp";
package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "/WEB-INF/jsp/hello.jsp";
    }
}

 

必须要使用全限定名

(2).forward进行转发

 return "forward:/WEB-INF/jsp/hello.jsp";
package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "forward:/WEB-INF/jsp/hello.jsp";
    }
}


 

(3).redirect进行重定向(访问不到WEB-INF)

 return "redirect:/WEB-INF/jsp/hello.jsp";
package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "redirect:/WEB-INF/jsp/hello.jsp";
    }
}

 

(4).redirect进行重定向访问(非WEB-INF文件夹)

  return "redirect:/a.jsp";
package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "redirect:/a.jsp";
    }
}

 

(5).转发会走视图解析器,重定向不会走视图解析器

视图解析器配置

<?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
       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.Jsxs.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>

 

Controller

package Com.Jsxs.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 Controller5 {
   
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
   
        HttpSession session = request.getSession();
        session.setAttribute("msg","通过Session进行获取");
        return "redirect:/a.jsp";
    }
}

 

重定向: 路径发生了变化

转发: 转发成功后路径没有变化

3.转发和重定向

(1).转发和重定向的含义

WEB-INF 目录是对客户端进行隐藏的,是服务器级别,所以重定向不到,要想访问得到需要写Controller处理
转发:属于内部访问,可以访问WEB-INF下面的文件夹
重定向: 属于外部访问,不可以访问WEB-INF下面的文件夹

(2).转发和重定向的区别

  • 转向URL不会变化,重定向URL会变化。
  • 转发才会走视图解析器,重定向不会走试图解析器

(十)、数据处理(前后端数据交互)

1.前端传递给后端数据【request,respone】

实体类

package Com.Jsxs.pojo;

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

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

控制层

package Com.Jsxs.Controller;

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

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

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

    @GetMapping("/t1")
    public String test(String name, HttpServletRequest request, HttpServletResponse response){
   
//        1.接受到前端的数据
        System.out.println("接受到的前端数据为:"+name);
//        2.将结果返回给前端
            HttpSession session = request.getSession();
            session.setAttribute("msg",name);
        return "hello";
    }
}

 
http://localhost/SpringMVC_06_Controller_war_exploded/user/t1?name=%22%E6%9D%8E%E6%98%8E%22

2.前端给后端传数据【Model】

package Com.Jsxs.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 Controller6 {
   

    @GetMapping("/t1")
    public String test(String name, Model model){
   
//        1.接受到前端的数据
        System.out.println("接受到的前端数据为:"+name);
//        2.将结果返回给前端
            model.addAttribute("msg",name);
        return "hello";
    }
}

 

3.前端给后端传数据【注解】

package Com.Jsxs.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;
import org.springframework.web.bind.annotation.RequestParam;

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

    @GetMapping("/t1")
    public String test(@RequestParam("username") String name, Model model){
   
//        1.接受到前端的数据
        System.out.println("接受到的前端数据为:"+name);
//        2.将结果返回给前端
            model.addAttribute("msg",name);
        return "hello";
    }
}

 

只能当使用新起的名字才有效,旧名字没有效
新名字才能传递

4.前端给后端传递一个对象【对象】

1.接受前端用户传递的参数,判断参数的名字,假设名字直接在方法上,可以直接使用
2.传递的是一个对象,匹配User对象中的字段名;如果说名字一致则赋值,否则就不能进行赋值
如果使用对象的话,前端传递的参数名和对象名必须一致,否则直接为null

控制层

package Com.Jsxs.Controller;

import Com.Jsxs.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/user")
public class Controller6 {
   
    /*
        1.接受前端用户传递的参数,判断参数的名字,假设名字直接在方法上,可以直接使用
        2.传递的是一个对象,匹配User对象中的字段名;如果说名字一致则赋值,否则就不能进行赋值
     */
    @GetMapping("/t2")
    public String test2(User user,Model model){
   
        model.addAttribute("msg",user);
        return "hello";
    }
}

 
http://localhost/SpringMVC_06_Controller_war_exploded/user/t2?id=1&name=%22%E6%9D%8E%22&age=3

一一对应的操作
并不是一一对应的情况下

5.后端展现给前端数据(四种)

(1).Model

    @GetMapping("/t2")
    public String test2(User user,Model model){
   
        model.addAttribute("msg",user);
        return "hello";
    }

(2).Servlet进行获取

    @GetMapping("/t1")
    public String test(String name, HttpServletRequest request, HttpServletResponse response){
   
//        2.将结果返回给前端
            HttpSession session = request.getSession();
            session.setAttribute("msg",name);
        return "hello";
    }

(3).ModelAndView进行获取

    @GetMapping("/t3")
    public ModelAndView test3(String name){
   
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",name);
        modelAndView.setViewName("hello");
        return modelAndView;
    }

(4).ModelMap 【暂且不适用,还没掌握】

    @GetMapping("/t4")
    public String test4(String name){
   
        ModelMap modelMap=new ModelMap();
         modelMap.addAttribute("msg",name);
        return "hello";
    }

6.后端传入前端方法的对比

  • Model 只有寥寥几个方法只适合于存储数据,简化版
  • ModelMap 继承了LinkedMap,除了实现了自身的一些方法,同样实现了LinkedMap的方法和特性
  • ModelAndView 可以在储存数据的同时,可以进行设置返回逻辑视图

(十一)、乱码问题解决

1.form表单提交的方式是Post然而控制层是Get

Form表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/encoding/t1" method="post">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

控制层

package Com.Jsxs.Controller;

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

@Controller
@RequestMapping("/encoding")
public class EncodingController {
   

    @GetMapping ("/t1")
    public String test1(){
   
        return "hello";
    };
}

 

2.form表单提交转发出现乱码的问题

前端页面展示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/encoding/t1" method="post">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

控制层代码展现

package Com.Jsxs.Controller;

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

@Controller
@RequestMapping("/encoding")
public class EncodingController {
   

    @PostMapping ("/t1")
    public String test1(String name, Model model)
    {
   
        model.addAttribute("msg",name);
        return "hello";
    }
}


 

输入中文并且提交

提交转发后出现乱码数据

(1).过滤器解决乱码

过滤器类

package Com.Jsxs.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;


public class EncodingFilter implements Filter {
   

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

    }

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

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
   

    }
}

 

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">
<!--    配置DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!--  注册过滤器  -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>Com.Jsxs.filter.EncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

(2).Method的提交方式

GET: 方法不会出现乱码
POST: 可能会出现乱码

(3).SpringMVC 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">
<!--    配置DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <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>
    </filter-mapping>
</web-app>

 

(4).Tomcat配置中文UTF-8解决中文乱码


(十二)、JSON

1.什么是JSON?

前后端分离时代:
后端部署后端,提供接口,提供数据。

  • 对象
  • JSON

前端独立部署,负责渲染后端,展示数据。

  • HTML

(1).json的概念

JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率

2.JavaScript与JSON的区别

(1).JavaScript

在JavaScript 语言中,一切都是对象。因此,任何JavaScript支持的类型都可以通过JSON来表示,列入字符串,数字,对象,数组等。

  • 对象表示为键值对,数据由逗号分隔
  • 花括号表示为对象
  • 方括号表示数组

(2)JSON

JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对的键名写在前面并用双引号 " " 包裹,使用冒号 : 分割,然后接着是值

{
   "name": "吉士先生"}
{
   "age": 3}

(3).JavaScript与JSON的区别

  • JSON 是javaScript 对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串。
var obj={
   a: 'hello' , b: 'world'};  这是一个对象,注意见名也可以使用引号包裹
var json='{"a" : "hello" , "b" : "world"}';  这是一个JSON字符串,本质是一个字符串

JSON和JavaScript对象互转

  • 要实现从JSON字符串转换为JavaScript对象,使用JSON.parse()方法
var obj=JSON.parse('{"a" : "hello" , "b" : "world"}'); 
 结果是javaScript对象:   {
   a: 'hello' , b: 'world'};  
  • 要实现从JavaScript对象转换为JSON字符串,使用JSON.stringify()方法
var obj=JSON.stringify({
   a: 'hello' , b: 'world'});
结果是JSON字符串 '{"a" : "hello" , "b" : "world"}'

(4).测试演练

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script type="text/javascript">
<!--    编写一个JavaScript对象-->

    var user={
     
        name : "吉士先生",
        sex : "26"
    };
    console.log(user);
  //  将js对象转换为JSON字符串
var json=JSON.stringify(user);
    console.log("js对象转换为JSON字符串为"+json);
  //  将JSON字符串转换为js对象
    var user2=JSON.parse(JSON.stringify(user));
    console.log(user2)
  </script>
</head>
<body>

</body>
</html>

 

(十三)、Controller转JSON数据

  • Jackson应该是目前比较好的json解析工具了
  • 当然工具不止这一个,比如还有阿里巴巴的fastjason
  • 我们这里使用Jackson,使用它需要导入它的jar包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

1.搭配环境

(0).去Aftrical里面导入lib目录

不要忘记新添加的jar包也要导入进去

(1).导入依赖

<?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">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>SpringMVC-07-JSON</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
<dependencies>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.10.0</version>
    </dependency>

</dependencies>
</project>

 

(2).配置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">
<!--    注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <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>
    </filter-mapping>
</web-app>

 

(3).配置spring.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
       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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--    扫描注解-->
    <context:component-scan base-package="Com.Jsxs.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>

 

2. toString

@ResponseBody   添加上此注解之后此方法就不会走视图解析器了,会返回你真实返回的东西,一般是字符串,实现了前后端分离
@RequestMapping(value = "/j1",produces = {
   "text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
package Com.Jsxs.Controller;

import Com.Jsxs.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
   

    @RequestMapping(value = "/j1",produces = {
   "text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody  // 添加上此注解之后此方法就不会走视图解析器了,会返回你真实返回的东西,一般是字符串,实现了前后端分离
    public String test(){
   
//        创建一个对象
        User user = new User("吉士先生",21,"男");
        String s = user.toString();
        return s;
    }
}


 

返回了对象的内容以字符串的形式;

3.解决JSON乱码的问题【必配】

过滤器解决的是字符集乱码的问题,这个解决的是JSON乱码问题
第一种决绝JSON乱码问题 【推荐】

<?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
       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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--    扫描注解-->
    <context:component-scan base-package="Com.Jsxs.Controller"/>
<!--     默认处理器-->
    <mvc:default-servlet-handler/>
<!--    驱动器-->
    <mvc:annotation-driven/>

<!--    JSON乱码问题配置-->
    <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>

<!--    视图解释器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

 

第二种解决JSON乱码问题 【不推荐】

@RequestMapping(value = "/j1",produces = {"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})

4.@ResponseBody 注解

@ResponseBody 添加上此注解之后此方法就不会走视图解析器了,会返回你真实返回的东西,一般是字符串,实现了前后端分离. 搭配着@Controller进行实现。

package Com.Jsxs.Controller;

import Com.Jsxs.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;

@Controller   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j1")
    @ResponseBody
    public String test() throws JsonProcessingException {
   

        ObjectMapper mapper = new ObjectMapper();
//        创建一个对象
        User user = new User("吉士先生",21,"男");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}

 

5.@RestController 注解

package Com.Jsxs.Controller;

import Com.Jsxs.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;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j1")
    public String test() throws JsonProcessingException {
   

        ObjectMapper mapper = new ObjectMapper();
//        创建一个对象
        User user = new User("吉士先生",21,"男");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}


 

6.Java对象转JSON字符串【对象】

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(user);
package Com.Jsxs.Controller;

import Com.Jsxs.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;

@Controller   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j1")
    @ResponseBody
    public String test() throws JsonProcessingException {
   

        ObjectMapper mapper = new ObjectMapper();
//        创建一个对象
        User user = new User("吉士先生",21,"男");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}


 

7.Java集合转JSON字符串【集合】

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(userList);
package Com.Jsxs.Controller;

import Com.Jsxs.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;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
   @RequestMapping("/j2")
    public String test2() throws JsonProcessingException {
   
        ObjectMapper mapper = new ObjectMapper();
        List<User> userList = new ArrayList<>();
//        创建一个对象
        User user = new User("吉士先生",21,"男");
        User user2 = new User("吉士先生2",21,"男");
        User user3 = new User("吉士先生3",21,"男");
        User user4 = new User("吉士先生4",21,"男");
        User user5 = new User("吉士先生5",21,"男");
        userList.add(user);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        String s = mapper.writeValueAsString(userList);
        return s;
    }
}

 

8.Java日期转JSON字符串【日期】

(1).输出的是时间戳

Date date = new Date();   输出的话会是一个 时间戳
date.toString();   输出的话会是一个 GMT
package Com.Jsxs.Controller;

import Com.Jsxs.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.Date;
import java.util.List;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j3")
    public String test3() throws JsonProcessingException {
   
        ObjectMapper mapper = new ObjectMapper();
//        创建一个对象
        Date date = new Date();
//        自定义日期格式

        String s = mapper.writeValueAsString(date.toString());
        return s;
    }
}

 

(2).时间戳转换为自定义日期格式

把时间戳转换为自定义的日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.format(date);
package Com.Jsxs.Controller;

import Com.Jsxs.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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   

    @RequestMapping("/j3")
    public String test3() throws JsonProcessingException {
   
        ObjectMapper mapper = new ObjectMapper();
//        创建一个对象
        Date date = new Date();
//        自定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = mapper.writeValueAsString(sdf.format(date));
        return s;
    }
}

 

(3).自定义日期格式+更改配置

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
package Com.Jsxs.Controller;

import Com.Jsxs.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j3")
    public String test3() throws JsonProcessingException {
   
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//        创建一个对象
        Date date = new Date();
//        自定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        String s = mapper.writeValueAsString(date);
        return s;
    }
}

 


(十四)、FastJson

1.什么是FastJson?

​在前后端数据传输交互中,经常会遇到字符串(String)与json,XML等格式相互转换与解析,其中json以跨语言,跨前后端的优点在开发中被频繁使用,基本上可以说是标准的数据交换格式。fastjson 是一个java语言编写的高性能且功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse 的性能提升到了极致.它的接口简单易用,已经被广泛使用在缓存序列化,协议交互,Web输出等各种应用场景中。可以方便的实现Json对象与JavaBean对象的转换,实现JavaBEAN对象与json字符串的转换。

2.搭配环境

(1).导入依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>

(2).在Aftrical里面的lib目录添加jar包

3.FastJson实战演练

System.out.println("********Java 对象 转 JSON 字符串*********");
        String s = JSON.toJSONString(userList);
        System.out.println("Java 对象转换Json字符串为:"+userList);

        System.out.println("\n********JSON 字符串 转 Java 对象*********");
        User user1 = JSON.parseObject(JSON.toJSONString(user2),User.class);
        System.out.println("JSON 字符串转换Java对象为:"+user1);
        System.out.println("\n********Java 对象 转 JSON 对象*********");
        JSONObject o = (JSONObject) JSON.toJSON(user2);
        System.out.println("Java 对象转换为JSON对象后为:"+o.getString("name"));
        System.out.println("\n********JSON 对象 转 Java 对象*********");
        User user6 = JSON.toJavaObject(o, User.class);
        System.out.println("JSON 对象转换Java 对象后为:"+user6);
package Com.Jsxs.Controller;

import Com.Jsxs.pojo.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController   //这个注解直接不走视图解析器了,实现前后端分离
public class UserController {
   
    @RequestMapping("/j4")
    public String test4(){
   
        List<User> userList = new ArrayList<>();
        User user = new User("吉士先生",21,"男");
        User user2 = new User("吉士先生2",21,"男");
        User user3 = new User("吉士先生3",21,"男");
        User user4 = new User("吉士先生4",21,"男");
        User user5 = new User("吉士先生5",21,"男");
        userList.add(user);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        System.out.println("********Java 对象 转 JSON 字符串*********");
        String s = JSON.toJSONString(userList);
        System.out.println("Java 对象转换Json字符串为:"+userList);

        System.out.println("\n********JSON 字符串 转 Java 对象*********");
        User user1 = JSON.parseObject(JSON.toJSONString(user2),User.class);
        System.out.println("JSON 字符串转换Java对象为:"+user1);
        System.out.println("\n********Java 对象 转 JSON 对象*********");
        JSONObject o = (JSONObject) JSON.toJSON(user2);
        System.out.println("Java 对象转换为JSON对象后为:"+o.getString("name"));
        System.out.println("\n********JSON 对象 转 Java 对象*********");
        User user6 = JSON.toJavaObject(o, User.class);
        System.out.println("JSON 对象转换Java 对象后为:"+user6);
        return s;
    }
}

 



转载:https://blog.csdn.net/qq_69683957/article/details/128425999
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场