https://springref.com/
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc%20Spring%20MVC
SpringMVC 控制器默认支持GET和POST两种方式,默认的是转发,而不是重定向。WEB-INF目录下的文件只能通过请求转发进行获取,重定向不能进行获取。
经典MVC模式中,M是指业务模型(Model–dao service),V是指用户界面(View – jsp),C则是控制器(Control–servlet),使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。其中,View的定义比较清晰,就是用户界面。
常见的服务端MVC框架:Struts,SpringMvc,ASP
常见的前端MVC框架: VUE React
依赖
<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
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.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>
SpringMVC是Spring Framework的一部分,是基于java实现的MVC的轻量级Web框架
不要导入: servlet jsp jstl 的这三个jar包到lib目录下,但是要存在于pom.xml里,否则会出现严重的500错误。切记。其他的依赖需要导入lib目录下
<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
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
<?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>
<?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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
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;
}
}
3.可以不创建新的web模板,我们只需要在创建Model的时候,我们应该对lib目录下进行添加如下几个内容,不能多。
SpringMVC的web框架围绕DispatcherServlet设计,DispatcherServlet的作用就是将请求分发到不同的处理器、从spring2.5开始,用户可以采用基于注解的controller声明方式。
DispatcherServlet表示前置控制器,是整个SpringMVC的控制核心。用户发出请求,DispatcherServlet接受请求并拦截请求。(映射就是)
HandlerMapping为处理器映射,DispatcherServlet调用HandlerMapping,HandlerMapping根据url查找 Handler
HandlerExpecution表示具体的Handler,其主要作用是根据url查找控制器,如url被查找控制为 : hello
HandlerExpecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等
HandlerAdpate表示处理适配器,其按照特定的规则去执行Handler
视图解析器的作用:
1.获取Model和view的数据
2.解析model和view的视图名字
3.拼接试图的名字,找到具体的视图
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>
<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>
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>
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;
}
}
(1).使用SpringMVC必须要配置的三大件:
处理器映射器 处理器适配器 视图解析器
(2).如果使用注解进行开发的话
那么 处理器映射器 处理器适配器 就会被自动注入,不用我们去配置了
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.视图解析器
<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>
<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>
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"; //会被试图解析器处理;
}
}
控制层
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>
@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>
并不是说一个网站又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 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
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文中的文件的名字一样,不能乱起名字
}
}
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";
}
}
我们要先访问类路径上的然后再访问方法路上的,相当于加了一层
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 一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。就是用于一个资源的定位操作。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
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
通过不同的请求方式来实现不同的效果!如下: 请求地址一样,但是功能可以不同!
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
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
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";
}
}
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";
}
}
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";
}
}
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";
}
}
@GetMapping("/add/{a}/{b}") get方式进行提交
@PostMapping("/add/{a}/{b}") post方式进行提交
@DeleteMapping("/add/{a}/{b}") delete方式进行提交
@PutMapping("/add/{a}/{b}") put方式进行提交
实质: 就是提交的方式不同,所以在路径相同的情况下访问的内容不同
首先创建一个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";
}
}
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对象,根据View的名称和视图解析器跳到指定的页面;
页面: {视图解析器前缀}+viewName+{视图解析器后缀}
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";
}
}
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";
}
}
因为在JSP中我们不能使用绝对路径,所以我们要使用EL表达式进行干涉
Spring
<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";
}
}
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";
}
}
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";
}
}
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";
}
}
视图解析器配置
<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";
}
}
WEB-INF 目录是对客户端进行隐藏的,是服务器级别,所以重定向不到,要想访问得到需要写Controller处理。
转发:属于内部访问,可以访问WEB-INF下面的文件夹
重定向: 属于外部访问,不可以访问WEB-INF下面的文件夹
实体类
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
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";
}
}
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";
}
}
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
@GetMapping("/t2")
public String test2(User user,Model model){
model.addAttribute("msg",user);
return "hello";
}
@GetMapping("/t1")
public String test(String name, HttpServletRequest request, HttpServletResponse response){
// 2.将结果返回给前端
HttpSession session = request.getSession();
session.setAttribute("msg",name);
return "hello";
}
@GetMapping("/t3")
public ModelAndView test3(String name){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",name);
modelAndView.setViewName("hello");
return modelAndView;
}
@GetMapping("/t4")
public String test4(String name){
ModelMap modelMap=new ModelMap();
modelMap.addAttribute("msg",name);
return "hello";
}
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";
};
}
前端页面展示
<%@ 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";
}
}
过滤器类
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>/*
GET: 方法不会出现乱码
POST: 可能会出现乱码
<?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>/*
前后端分离时代:
后端部署后端,提供接口,提供数据。
前端独立部署,负责渲染后端,展示数据。
JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
在JavaScript 语言中,一切都是对象。因此,任何JavaScript支持的类型都可以通过JSON来表示,列入字符串,数字,对象,数组等。
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对的键名写在前面并用双引号 " " 包裹,使用冒号 : 分割,然后接着是值。
{"name": "吉士先生"}
{"age": 3}
var obj={a: 'hello' , b: 'world'}; 这是一个对象,注意见名也可以使用引号包裹
var json='{"a" : "hello" , "b" : "world"}'; 这是一个JSON字符串,本质是一个字符串
JSON和JavaScript对象互转
var obj=JSON.parse('{"a" : "hello" , "b" : "world"}');
结果是javaScript对象: {a: 'hello' , b: 'world'};
var obj=JSON.stringify({a: 'hello' , b: 'world'});
结果是JSON字符串 '{"a" : "hello" , "b" : "world"}'
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<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>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.10.0version>
dependency>
不要忘记新添加的jar包也要导入进去
<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>org.examplegroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>SpringMVC-07-JSONartifactId>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.10.0version>
dependency>
dependencies>
project>
<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>
<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>
@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;
}
}
过滤器解决的是字符集乱码的问题,这个解决的是JSON乱码问题
第一种决绝JSON乱码问题 【推荐】
<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/>
<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;"})
@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;
}
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
把时间戳转换为自定义的日期格式
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;
}
}
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;
}
}
在前后端数据传输交互中,经常会遇到字符串(String)与json,XML等格式相互转换与解析,其中json以跨语言,跨前后端的优点在开发中被频繁使用,基本上可以说是标准的数据交换格式。fastjson 是一个java语言编写的高性能且功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse 的性能提升到了极致.它的接口简单易用,已经被广泛使用在缓存序列化,协议交互,Web输出等各种应用场景中。可以方便的实现Json对象与JavaBean对象的转换,实现JavaBEAN对象与json字符串的转换。
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
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;
}
}