管他会不会,先跑一个
创建项目
略过~
导包
<!-- 一个一个导太麻烦,直接导入spring-webmvc包会将 aop、beans、context、core、web、webmvc等包一次导入 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
配置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"
metadata-complete="true">
<!-- 注册DispatcherServlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- init-param:初始化参数 配置springmvc的配置文件,在启动的时候初始化 -->
<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>
<!-- 默认的配置DispatcherServlet屏蔽了html页面的访问,如果需要使用html你需要加上如下: -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
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名称网址处理程序映射 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 简单控制器处理程序适配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- <bean class="org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter" abstract="true"/>-->
<!-- 试图解析器:配置了这个 在controller只需要输入html(jsp等)名称,就会自动补全为:/WEB-INF/xx.html -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 注册自己写的controller -->
<bean id="/hello" class="com.qc.controller.HelloSpringmvc"/>
</beans>
controller
package com.qc.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author c
* @create: 2021-03-28 02:42
*/
public class HelloSpringmvc implements Controller {
//传统servlet继承httpservlet,springmvc继承Controller接口,实现handleRequest方法
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//模型和视图
ModelAndView modelAndView = new ModelAndView();
//放入要返回的数据
modelAndView.addObject("msg","hello springmvc");
//要跳转的页面 经过视图解析器解析为 /WEB-INF/jsp/hello.jsp
modelAndView.setViewName("hello");
return modelAndView;
}
}
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
结果
在tomcat部署运行
![]()
终极奥秘
![]()
原理
- HandlerMapping为处理器映射,DispacherServlet调用,HandlerMapping根据请求url查找Handler
- HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器
- HandlerExection将解析后的信息传递给DispacherServlet
- HandlerAdapter表示处理适配器,其按照待定的规则去执行handler
- Handler让具体的controller执行
- controller将具体执行信息返回给HandlerAdapter(ModelAndView)
- HandlerAdapter将视图逻辑或模型传递给DispacherServlet
- DispacherServlet调用视图解析器(viewResolver)来解析HandlerAdapter传递的逻辑视图名
- 视图解析器的逻辑视图名传递给DispcherServlet
- DispacherServlet根据视图解析器解析的视图结果,调用具体视图,最终呈现给用户
使用注解
xml配置
固定的
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.qc"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
controller
package com.qc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author c
* @create: 2021-03-28 21:12
*/
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","hello springmvc-anno");
return "hello";
}
}
Restfull风格
传统url通过?号传参,例如:
http://localhost:8080/mvc/hello?a=1&b=6
不简洁,不美观,还不安全
Restfull:
![]()
美观、简介的同时还安全(不知道传入的参数是什么,干嘛的)
使用
在springmvc中使用 @PathVariable 注解去标记这是restfull风格的参数。
简单示例
@Controller
public class HelloController {
//在请求后面直接/{属性名}匹配参数
@RequestMapping("/hello/{a}/{b}")
//在字段前加上@PathVariable表示示restfull,会自动去请求上匹配参数
public String hello(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","hello springmvc-anno");
System.out.println(a+b);
return "hello";
}
}
Http动词
- GET(SELECT):从服务器取出资源(一项或多项)。
- POST(CREATE):在服务器新建一个资源
- PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
- PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
- DELETE(DELETE):从服务器删除资源。
使用
有两种方式:
- 在@RequestMapping中指定:@RequestMapping(value = “/hello/{a}/{b}”,method = RequestMethod.GET)
- 使用具体的注解:@GetMapping(“/hello/{a}/{b}”)
技巧
restfull会根据请求类型匹配controller
例如:
两个一样的方法,可以根据不同的请求类型自动匹配
@Controller
public class HelloController {
//在请求后面直接/{属性名}匹配参数
// @RequestMapping(value = "/hello/{a}/{b}",method = RequestMethod.GET)
@GetMapping("/hello/{a}/{b}")
//在字段前加上@PathVariable表示示restfull,会自动去请求上匹配参数
public String hello(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","GetMapping");
System.out.println(a+b);
return "hello";
}
@PostMapping("/hello/{a}/{b}")
//在字段前加上@PathVariable表示示restfull,会自动去请求上匹配参数
public String hello2(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","PostMapping");
System.out.println(a+b);
return "hello";
}
}
post请求:
![]()
get请求:
![]()
重定向和请求转发
请求转发(forward)
默认就是请求转发
return "hello";
重定向
//将请求重定向到 @GetMapping("/hello/{a}/{b}")
@PostMapping("/hello/{a}/{b}")
//在字段前加上@PathVariable表示示restfull,会自动去请求上匹配参数
public String hello2(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","PostMapping");
System.out.println(a+b);
return "redirect:/hello/"+a+"/"+b;
}
乱码过滤
springmvc有自带的编码过滤器:CharacterEncodingFilter 我们只需要在web.xml中配置使用就行了
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>edcoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
js中Json到对象的转换
<script type="text/javascript">
//声明一个对象
var user={
name:"",
age:18
};
//打印
console.log(user);
//转换为json
var json = JSON.stringify(user);
console.log(json)
//将json转换为对象
var user2 = JSON.parse(json);
console.log(user2)
</script>
java中json的使用
Jcakson
导包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
代码
@RequestMapping("/t")
@ResponseBody //不走视图解析器,不跳转页面,直接返回一个字符串
public String test(String name) throws JsonProcessingException {
User user = new User(1,"张三",18);
System.out.println(user);
//创建ObjectMapper对象(jackson使用这个对象来实现json的转换)
ObjectMapper objectMapper = new ObjectMapper();
//将user对象转换为json格式
String s = objectMapper.writeValueAsString(user);
System.out.println(s);
return s;
}
结果
![]()
我们发现出现了中文乱码
中文乱码处理
方式一
在Mapping中加入produces = "application/json;charset=utf-8"参数
@RequestMapping(value = "/t",produces = "application/json;charset=utf-8")
方式二
<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>
![]()
乱码处理了。
提示:我们不可能在每个Mapping上加一样的参数,这样太繁琐了,所以一般使用第二种,全局只需要配置一次。
FastJson
fastjson是阿里开发的一款专门用于java开发的包,可以方便的实现json对象与javaBean之间的转换。
fastjson有三个主要的类:
- JSONObject代表json对象
- JSONArray代表json对象数组
- JSON代表JSONObject和JSONArray的转化
导包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
简单使用
@RequestMapping("/t2")
@ResponseBody //不走视图解析器,不跳转页面,直接返回一个字符串
public String test2(String name) {
User user = new User(1,"张三",18);
System.out.println(user);
//JSON.toJSONString(user) 将javabean转为json
String s = JSON.toJSONString(user);
System.out.println(s);
//将json字符串转换为javaBean
User user2 = JSON.parseObject(s, User.class);
System.out.println(user2);
return s;
}
也有乱码问题。