B站学习传送门==>【狂神说Java】SpringMVC最新教程IDEA版通俗易懂
感谢狂神?
M即model模型是指模型表示业务规则。 V即View视图是指用户看到并与之交互的界面。 C即controller控制器是指控制器;接受用户的输入并调用模型和视图去完成用户的需求.
1.回顾servlet
创建新的maven,在pom.xml 文件中进行相关配置.
删除src目录,将当前项目作为父级根项目
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
检查maven的地址;
创建新的模块;作为子目录项目;
添加框架支持
写个DemoServlet类
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 Demo01Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mark = req.getParameter("mark");
if(mark.equals("my")){
req.getSession().setAttribute("message","返回的是My");
}else if(mark.equals("you")){
req.getSession().setAttribute("message","返回的是You");
}
req.getRequestDispatcher("/index.jsp").forward(req,resp);
}
}
在web.xml配置servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>Demo01Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: 小智
Date: 2021/10/6
Time: 18:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>复习servlet</title>
</head>
<body>
${message}
<form action="demo" method="post">
点击按钮
<input type="submit" name="mark" value="my"><br/>
<input type="submit" name="mark" value="you"><br/>
</form>
</body>
</html>
启动后,点击按钮my
2.SpringMVC概述
官方文档地址::4.3.24版本文档
可进入
https://docs.spring.io/spring-framework/docs/4.3.24.RELEASE/spring-framework-reference
点击html
可找到这里mvc相关的.
https://docs.spring.io/spring-framework/docs/4.3.24.RELEASE/spring-framework-reference/html/mvc.html
当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者.
SpringMVC来自于SpringFramework,基于Java实现的MVC轻量级Web框架。 Spring的web框架核心是DispatcherServlet DispatcherServlet 可以管理不同的部分
先快速搭建一下;
配置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>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>
在resources 目录下创建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"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/demos/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="/demo" class="com.xiaozhi.controller.DemoController"/>
</beans>
写个控制层
package com.xiaozhi.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 DemoController implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("message","SpringMVC显示");
mv.setViewName("demo");
return mv;
}
}
demo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>试试MVC</title>
</head>
<body>
${message}
</body>
</html>
配置tomcat;
大概的布局为;
访问 http://localhost:8080/study02_fasttry/demo
开始运行时出现404错误;检查了jar包后,没有缺少的; 然后就去给项目手动添加了相关的所有jar包;
然后再启动后访问;
3. SpringMVC执行原理
刚才在fwhttp://localhost:8080/study02_fasttry/demo 时,可分为3部分; http://localhost:8080 服务器域名; study02_fasttry 在tomcat部署的web站点; demo 控制器
DispatcherServlet 为前置控制器,是springmvc的控制核心.客户端发出请求后,由它接收请求,拦截请求.
4.深入理解
试试再写一次配置步骤;
需要注意的是,在配置springmvc 时, 用/ 和/* 有区别; / 仅匹配所有的请求,不会去匹配jsp页面; /* 匹配所有的请求以及jsp页面
配置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>deepspringmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-deepspringmvcservlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>deepspringmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在resources 目录下写springmvc-deepspringmvcservlet.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"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/demos/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="/demo2" class="com.xiaozhi.controller.DeepStudyMvc"/>
</beans>
简易控制层
package com.xiaozhi.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 DeepStudyMvc implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message","再次学习");
modelAndView.setViewName("demo2");
return modelAndView;
}
}
demo2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>深入理解MVC</title>
</head>
<body>
${message}
</body>
</html>
手动导包
访问页面时输入demo2
5.使用注解进行springmvc的配置
基本工作完成后,
demo04.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学习用注解开发</title>
</head>
<body>
${message}
</body>
</html>
先去添加lib 目录
编写配置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>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-commentdevelop.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>
资源目录名一致即可;
编写springmvc-commentdevelop.xml Spring MVC配置文件;
(1)先配置包扫描;使用自动扫描包,让指定包下的注解生效,由IOC容器统一管理;
<context:component-scan base-package="com.xiaozhi.controller"/>
(2)默认为servlet;不去处理其他静态资源
<mvc:default-servlet-handler />
(3)设置支持mvc注解驱动(代替处理器映射器和处理器适配器),以及视图解析器配置
总设置为
<?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.xiaozhi.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层,直接用注解@Controller 即可,不用去实现接口了. @Controller注解类型用于声明Spring类的实例是一个控制器
注意return的是视图名称;和前后缀配合使用;
@Controller
public class Demo04Controller {
@RequestMapping("/demo04")
public String demo(Model model){
model.addAttribute("message","学习用注解开发配置springmvc");
return "demo04";
}
}
还可在controller的类上加@RequestMapping 注解;进行多级url地址配置;
例如
@RequestMapping("/demo")
访问时的路径就为项目名/demo/demo04 了.
ok,配置tomcat;
然后启动服务; 按照项目名/demo/demo04 的方式访问; http://localhost:8080/study04_comment/demo/demo04
好耶,设置的参数显示出来了.
6. controller配置小结
控制器负责提供访问应用程序的行为(解析用户的请求并将其转换为一个模型 ), 通过接口定义或注解定义 两种方法实现。 一个控制器类可包含多个方法
快速完成搭建
首先看看实现Controller接口的方式
注意,用这种方式的话; 一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦
实现此接口,即表名此类为控制器.
位于import org.springframework.web.servlet.mvc.Controller 包下;函数式接口Controller
OK,试试实现接口的方式;
package com.xiaozhi.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 DemoController01 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView =new ModelAndView();
modelAndView.addObject("name","使用实现接口的方式试试");
modelAndView.setViewName("demo01");
return modelAndView;
}
}
配置springmvc-controller.xml ;
注册请求的bean;name对应请求路径,class对应处理请求的类
注意,用这种实现接口的方式,就不用去配置包扫描,之类的;仅需要
<?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">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="/demo01" class="com.xiaozhi.controller.DemoController01"/>
</beans>
设置好tomcat后,访问路径demo01
使用注解的方式
这里用renturn返回的视图就可以直接被视图解析器解析; @RequestMapping中的就是请求url路径
且用注解的话;在一个controller中可以写多个方法;
package com.xiaozhi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DemoController02 {
@RequestMapping("/demo02")
public String use01(Model model){
model.addAttribute("name","用注解的方式");
return "demo02";
}
}
配置springmvc-controller.xml 时;不用手动去配置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.xiaozhi.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>
访问路径即可
7.@RequestMapping
@RequestMapping注解 用于映射url到控制器类或一个特定的处理程序方法。 可用于类或方法上。 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
案例: (1)先试试仅在方法上加注解 @RequestMapping
@Controller
public class DemoController03 {
@RequestMapping("/onlyMethod")
public String res(Model model){
model.addAttribute("result","仅在方法上加请求路径");
return "demo03";
}
}
访问即可;
(2)在类上,方法上使用注解; 此时类上的注解就相当于一个父级的url地址;
@Controller
@RequestMapping("/father")
public class DemoController03 {
@RequestMapping("/firstSon")
public String res1(Model model){
model.addAttribute("result","同时在类和方法上加请求路径-->此时为demo03页面");
return "demo03";
}
@RequestMapping("/secondSon")
public String res2(Model model){
model.addAttribute("result","同时在类和方法上加请求路径-->此时为demo04页面");
return "demo04";
}
}
访问:
若仅用类上的地址;由于没有写返回的视图页面;无法找到;
访问http://localhost:8080/study05_controller/father/firstSon
访问http://localhost:8080/study05_controller/father/secondSon
但是建议可以直接在方法上就把路径拼接好.
8. Restful资源定位及资源操作的风格
用这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 资源:互联网所有的事物都可以被抽象为资源 资源操作:使用POST(添加 )、DELETE(删除 )、PUT(修改 )、GET(查询 ), 使用不同方法对资源进行操作。
案例使用;
(1)之前的方式,前面传入的参数必须对应拼接
demo01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>demo01</title>
</head>
<body>
显示result==>${result}
</body>
</html>
写个简易控制类试试
@Controller
public class AboutRestfulControllerTest01 {
@RequestMapping("/add")
public String test01(int a , int b, Model model){
int result = a+b;
model.addAttribute("result",result);
return "demo01";
}
}
访问时拼接url参数
http://localhost:8080/study06_aboutrestfull/add?a=10&b=15
(2)试试Restful风格
需要使用注解@PathVariable 指明路径变量;让方法参数的值对应绑定到一个URI模板变量上。
@Controller
public class AboutRestfulControllerTest01 {
@RequestMapping("/add/{a}/{b}")
public String test01(@PathVariable int a ,@PathVariable int b, Model model){
int result = a+b;
model.addAttribute("result",result);
return "demo01";
}
}
这时再用原来的方式进行访问请求是找不到的
就按照restful的格式;直接放入参数的数字
http://localhost:8080/study06_aboutrestfull/add/10/15
当然,后面的路径参数变量也可指定设置为其他类型的;
键入@RequestMapping 注解;注意到有个枚举类RequestMethod 的数组;
键入枚举类RequestMethod
使用method属性指定请求类型
@Controller
public class AboutRestfulControllerTest01 {
@RequestMapping(value = "/add/{a}/{b}",method = {RequestMethod.GET})
public String test01(@PathVariable int a ,@PathVariable int b, Model model){
int result = a+b;
model.addAttribute("result",result);
return "demo01";
}
}
当然,也可以直接用注解,里面放入请求地址即可 @PatchMapping("") @GetMapping(" ") @PostMapping(" ") @DeleteMapping(" ") @PutMapping(" ")
案例:
比如说写个@PutMapping("") 方式的修改请求;
@Controller
public class AboutRestfulControllerTest01 {
@PutMapping("/add/{a}/{b}")
public String test01(@PathVariable int a, @PathVariable int b, Model model) {
int result = a + b;
model.addAttribute("result", result);
return "demo01";
}
}
但是此时浏览器默认的访问是get方式;
还有一种情况,比如说相同的路径写了不同的请求方式 ; 那么他就会找自己对应的方式;
@Controller
public class AboutRestfulControllerTest01 {
@PutMapping("/add/{a}/{b}")
public String test01(@PathVariable int a, @PathVariable int b, Model model) {
int result = a + b;
model.addAttribute("result", result);
return "demo01";
}
@GetMapping("/add/{a}/{b}")
public String test02(@PathVariable int a, @PathVariable int b, Model model) {
int result = a + b;
model.addAttribute("result", result);
return "demo01";
}
}
但是,如果在相同的路径写了相同的请求方式 ;
访问时就会出现访问抉择不当异常;
9.重定向,转发
HttpServletRequest实现转发
HttpServletResponse实现重定向
(1)案例,没有视图解析器时
先将配置文件springmvc-controller.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
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.xiaozhi.controller"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
</beans>
a.然后返回时直接页面写死;强制转发.
@Controller
public class Controller02 {
@RequestMapping("/test01")
public String test(Model model){
model.addAttribute("res","不用视图解析器,此参数回过去了吗;");
return "/WEB-INF/jsp/demo02.jsp";
}
}
访问http://localhost:8080/study06_aboutrestfull/test01
b.使用重定向redirect
@Controller
public class Controller02 {
@RequestMapping("/test01")
public String test(Model model){
model.addAttribute("res","resultdirect;");
return "redirect:/index.jsp";
}
}
访问http://localhost:8080/study06_aboutrestfull/test01
c.转发2forward
@Controller
public class Controller02 {
@RequestMapping("/test01")
public String test(Model model){
model.addAttribute("res","resultforward;");
return "forward:/index.jsp";
}
}
访问http://localhost:8080/study06_aboutrestfull/test01
(2)案例,有视图解析器时
把视图解析器加回去
<?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.xiaozhi.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>
a.转发
@Controller
public class Controller02 {
@RequestMapping("/test02")
public String test(Model model){
model.addAttribute("res","转发;");
return "demo02";
}
}
访问http://localhost:8080/study06_aboutrestfull/test02
b.重定向
@Controller
public class Controller02 {
@RequestMapping("/test02")
public String test(Model model){
model.addAttribute("res","重定向;");
return "redirect:/index.jsp";
}
}
访问http://localhost:8080/study06_aboutrestfull/test02
10.接收请求参数&数据回显
首先把lombok插件的包下过来,在pom.xml 文件中配置
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
插件实体类User
package com.xiaozhi.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
👀 接收请求参数
(1)提交的域名称和处理方法的参数名一致或者不一致时
先试试字符串的接收
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/u1")
public String user(String name, Model model){
System.out.println("前端输入的name为"+name);
model.addAttribute("toName",name);
return "ituser";
}
}
ituser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
返回的是==>${toName}
</body>
</html>
启动服务器后访问http://localhost:8080/study06_aboutrestfull/user/u1?name=张三
要是这里访问时,拼接url;把name改了之后; http://localhost:8080/study06_aboutrestfull/user/u1?namessss=张三
虽然参数取不到,但是可以跳转页面;
OK,看看方式2= = >
(2)注解解决提交参数不一致的问题
在方法的参数前使用注解@RequestParam(" ")
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/u1")
public String user(@RequestParam("namesssssssss") String name, Model model){
System.out.println("前端输入的name为"+name);
model.addAttribute("toName",name);
return "ituser";
}
}
访问http://localhost:8080/study06_aboutrestfull/user/u1/?namesssssssss=张三
然后试试用别的参数访问,比如说name; http://localhost:8080/study06_aboutrestfull/user/u1/?name=%E5%BC%A0%E4%B8%89
就会直接提示参数不对;
(3)提交的数据是一个对象时
实际的执行流程,接收到前端传入的参数;匹配对象的字段,调用get方法;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/u1")
public String user(User user,Model model){
System.out.println("得到输入的值=>"+user);
model.addAttribute("toUser",user);
return "ituser";
}
ituser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
返回的是==>${toUser}
</body>
</html>
访问http://localhost:8080/study06_aboutrestfull/user/u1?name=%E5%BC%A0%E4%B8%89&age=18
👀数据回显
通过ModelAndView以及通过Model,之前有案例.
别的方式;例如通过ModelMap
通过ModelMap
可以先看看Model接口
他有个实现类继承ModelMap 类
ModelMap 类是继承了LinkedHashMap;它具有LinkedHashMap的特性和方法;
11.乱码问题解决
模拟登陆页面login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>这是表单</title>
</head>
<body>
<form action="/login/t1" method="post">
名字:<input name="name" type="text"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
显示页面demo03.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
</body>
</html>
模拟处理业务
@Controller
public class EncodingController{
@PostMapping("/login/t1")
public String test(String name,Model model){
model.addAttribute("message",name);
return "demo03";
}
}
提交时,出现乱码
编写过滤器解决问题
public class EncodingFilter implements Filter{
String encode;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("字符编码过滤初始化");
encode = filterConfig.getInitParameter("encode");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("字符编码过滤中.......................");
servletRequest.setCharacterEncoding(encode);
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("字符编码过滤销毁");
}
}
在web.xml 中配置
<filter>
<filter-name>encodfilter</filter-name>
<filter-class>com.xiaozhi.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
问题解决
当然 ,也可以用springmvc自带的编码过滤;
直接就不用自己写的过滤器了 在web.xml 中加入即可
<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>
12.什么是Json
轻量级的数据交换格式; 可将Java语言转为 json格式的字符串,然后由json字符串转为javaScript语言;
键值对的形式:
JavaScript 对象转为JSON字符串
JSON.stringify(js对象.) 方法
JSON字符串转为JavaScript对象 JSON.parse( .....注意这里要放json格式的字符串)
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var user={
account:"张三",
password:136523
};
var toJson = JSON.stringify(user);
console.log("由js对象转为Json====>")
console.log(toJson);
var toJavaScript = JSON.parse(toJson);
console.log("由JSON格式转为JavaScript===>");
console.log(toJavaScript);
</script>
</head>
<body>
</body>
</html>
13.JackSon
先在pom.xml 文件,导入jackson的maven依赖,
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
写个实体类User;用lombok的注解
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private String password;
private int age;
}
使用注解@ResponseBody ,可避免返回时通过视图解析器;而是直接返回一个字符串; (也可以在整个业务层的类上使用注解@RestController ,表示此类下的所有方法都会返回的是json字符串.)
试着这次直接去用toString( )返回的字符串.
@Controller
public class UserController {
@ResponseBody
@RequestMapping("/jackson01")
public String testJson(){
User user=new User("小智","789654",22);
String s = user.toString();
return s;
}
}
确实返回了字符串,但中文有显示不当问题.
,用jackson试试;
注意,需要用到ObjectMapper对象;
@Controller
public class UserController {
@ResponseBody
@RequestMapping("/jackson01")
public String testJson() throws JsonProcessingException {
User user=new User("小智","789654",22);
ObjectMapper objectMapper = new ObjectMapper();
String asString = objectMapper.writeValueAsString(user);
return asString;
}
}
OK,显示为JSON格式的;
json乱码问题解决
这里的乱码问题还是要解决的,在 注解@RequestMapping 的参数 produces 处设置字符编码;
@RequestMapping(value = "/jackson01",produces = "application/json;charset=utf-8")
加上编码设置后;
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01", produces = "application/json;charset=utf-8")
public String testJson() throws JsonProcessingException {
User user = new User("小智", "789654", 22);
ObjectMapper objectMapper = new ObjectMapper();
String asString = objectMapper.writeValueAsString(user);
return asString;
}
}
但是,每次需要的请求位置都需要去设计编码; 那么一次性解决问题; 在springmvc配置文件中配置即可
<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>
将集合转为json格式的字符串
案例;将不同的用户对象放入集合中,转为json格式的字符串;
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01")
public String testJson() throws JsonProcessingException {
User user0 = new User("小智", "7896asdas54", 22);
User user1 = new User("小智", "78dasda4", 22);
User user2 = new User("小智", "weqweqq", 23);
User user3 = new User("小智", "7asdada4", 22);
User user4 = new User("小智", "7896vxzvxz54", 22);
List<User> userList =new ArrayList<User>();
userList.add(user0);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
ObjectMapper objectMapper = new ObjectMapper();
String asString = objectMapper.writeValueAsString(userList);
return asString;
}
}
访问; [ { "键" : "值","键" : "值",... },{"键" : "值","键" : "值",... } ]
将日期转为json格式的字符串
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01")
public String testJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
String asString = objectMapper.writeValueAsString(date);
return asString;
}
}
访问,返回的是时间戳数字
(1)尝试用SimpleDateFormat 日期格式转化
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01")
public String testJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(date);
String asString = objectMapper.writeValueAsString(format);
return asString;
}
}
访问,格式转化了;
(2)使用ObjectMapper格式化日期;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01")
public String testJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(simpleDateFormat);
Date date = new Date();
String asString = objectMapper.writeValueAsString(date);
return asString;
}
}
(3)也可以直接把这样的转换方式封装起来;
public class JsonDate {
public static String getJson(Object object) {
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
需要用的时候直接去调用;
@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/jackson01")
public String testJson() throws JsonProcessingException {
Date date = new Date();
return JsonDate.getJson(date);
}
}
14.FastJson
先去pom.xml 文件导入maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
JSONObject 代表 json 对象 ; JSONArray 代表 json 对象数组
(1)java对象集合转json字符串;JSON.toJSONString(java对象 ) (2)json字符串转 java对象JSON.parseObject(json字符串,要转的java对象的类反射) (3)Java对象转为json对象 JSON.toJSON(java对象) (4) json对象转为java对象JSON.toJavaObject(json对象, 要转的java对象的类反射)
15.初遇Ajax
AJAX ( Asynchronous JavaScript and XML ) 异步JavaScript与XML.
可实现不刷新页面就发出请求.
先把基础的配置搭好 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>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-controller.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>
springmvc-controller.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
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.xiaozhi.controller"/>
<mvc:default-servlet-handler />
<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>
简易业务测试
@RestController
public class DemoController {
@RequestMapping("/test01")
public String test01(){
return "test01";
}
}
在html中使用iframe内联,试试效果; demo01.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe内联</title>
</head>
<body>
<iframe src="https://blog.csdn.net/MrTumnus/article/details/117924752" width="100%" height="600px" frameborder="0"></iframe>
</body>
</html>
实际上,src这里不会直接写死;
试试用iframe内联框架伪造阿贾克斯;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe内联伪造阿贾克斯</title>
<script type="text/javascript">
function toGet(){
var textVal = document.getElementById("thetext").value;
document.getElementById("show").src = textVal;
}
</script>
</head>
<body>
<div>
<input type="text" id="thetext" placeholder="输入内容"><br/>
<input type="button" value="获取网页" onclick="toGet()">
</div>
<div>
<iframe id="show" style="width: 100%; height: 700px" ></iframe>
</div>
</body>
</html>
使用jquery封装的阿贾克斯
在jquery官网下载jquery库
https://jquery.com/download/
下载开发版本的即可;
先把它放到要用的地方;
由源码可见,发送请求时,也就是url地址,请求类型,提交的资源,响应的资源;…
案例:
输入框失去焦点时,就会提交post请求;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>试试ajax</title>
<%--部署引入jquery--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
function toRun(){
$.post({
/*请求url*/
url:"${pageContext.request.contextPath}/test02",
/*提交的数据*/
data: { "account" : $("#thetext").val()},
/*响应的数据;*/
success:function (data){
alert(data)
}
});
}
</script>
</head>
<body>
<%--输入框失去焦点就触发--%>
<input type="text" id="thetext" name="account" placeholder="失去焦点就会触发" οnblur="toRun()">
</body>
</html>
简易业务层处理;
@RestController
public class DemoController {
@RequestMapping("/test02")
public void test02(String account, HttpServletResponse response) throws IOException {
System.out.println("获取参数为=>"+account);
if("小智".equals(account)){
response.getWriter().print("OK");
}else {
response.getWriter().print("error!!!");
}
}
}
流程原理:
jQuery.ajax(...)
部分参数:
url:请求地址
type:请求方式,GET、POST(1.9.0之后用method)
headers:请求头
data:要发送的数据
contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否异步
timeout:设置请求超时时间(毫秒)
beforeSend:发送请求前执行的函数(全局)
complete:完成之后执行的回调函数(全局)
success:成功之后执行的回调函数(全局)
error:失败之后执行的回调函数(全局)
accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
dataType:将服务器端返回的数据转换成指定类型
"xml": 将服务器端返回的内容转换成xml格式
"text": 将服务器端返回的内容转换成普通文本格式
"html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
"script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
"json": 将服务器端返回的内容转换成相应的JavaScript对象
"jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
16.Ajax异步加载数据
写个实体类感受一下,异步加载的效果
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String account;
private String password;
private int age;
}
存入数据
@RestController
public class DemoController {
@RequestMapping("/user")
public List<User> toShow(){
List<User> list = new ArrayList<User>();
list.add(new User("数据1号","123",22));
list.add(new User("2号","123",44));
list.add(new User("3号","123",62));
return list;
}
}
访问http://localhost:8080/user
简易的jsp,点击按钮触发;
<%--
Created by IntelliJ IDEA.
User: 小智
Date: 2021/10/16
Time: 17:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>简易显示</title>
<%--部署JQuery--%>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function (){
$("#btn").click(function (){
$.post("${pageContext.request.contextPath}/user",function (res){
var str="";
for (var i = 0; i < res.length; i++) {
str+="<tr>";
str+="<td>"+res[i].account+"</td>";
str+="<td>"+res[i].password+"</td>";
str+="<td>"+res[i].age+"</td>";
str+="</tr>";
}
$("#table").append(str);
})
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="点击我">
<table width="100%" border="1" cellspacing="0" id="table">
<tr>
<th>账号</th>
<th>密码</th>
<th>年龄</th>
</tr>
</table>
</body>
</html>
17.springMVC拦截器
写个类去实现接口HandlerInterceptor
public class DemoInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理之前");
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("处理------------>");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("结束后清理==------>");
}
}
在springmvc配置文件中标注
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.xiaozhi.config.DemoInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
去访问发出请求时,就被拦截;
若在配置时改为;
public class DemoInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理之前");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("处理------------>");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("结束后清理==------>");
}
}
访问请求就会放行
|