目录
第一种方法 采用类型映射让资源路径不仅如此前端控制器 (不推荐使用)
第二种方法: 可以在springmvc中声明某些资源是静态资源
2.5 @RequestBody将json格式的字符串封装为自定义类型
同名:在handler的形参列表中定义一个形参,形参名称和请求参数的名称一致,在执行handler时,请求参数参数会自动封装到形参中,并且可以进行默认的类型转化 (类型转化出现异常---即形参为Integer请求参数是String 就会发生类型转换异常)
- //简单数据类型的封装 同名的---形参和请求参数的名称相同
- @RequestMapping(value = "/test10")
- public ModelAndView test10(String name,Integer age,Integer sex) {
- ModelAndView model=new ModelAndView("/test.jsp");
- model.addObject("name", name);
- model.addObject("name1", age);
- model.addObject("name2", sex);
- return model;
- }
请求参数的名称和形参的名称不一致的时候,使用参数级别的注解 @RequestParam(指定映射规则)
- //简单数据类型的封装 不同名 --使用参数级别的注解@RequestParam
- //属性 name:用于指定请求参数的名称
- //required :当前参数是否必填
- //defaultValue 代表如果required=true,设置了默认值后,请求参数可以不传递 --采取默认值
- @RequestMapping(value = "/test11")
- public ModelAndView test11(@RequestParam(name="Username",required = true,defaultValue = "moren")String name,Integer age,Integer sex) {
- ModelAndView model=new ModelAndView("/test.jsp");
- model.addObject("name", name);
- model.addObject("name1", age);
- model.addObject("name2", sex);
- return model;
- }
优缺点 :1.优化了servlet的请求参数获取方式 (无序使用req.getParameter(name)获取)
2.如果请求参数过多的话,方法的形参列表过长
因此出现了自定义的pojo类型
springmvc会自动根据形参中自定义类型的参数的属性名和请求参数名进行封装(如果请求参数名称和形参中某个属性名称一致,自动进行封装) 和形参名没有任何关系
- //自定义pojo的封装
- //请求参数与形参的名称无关 ,只有 形参对应的属性名有关 属性名相同进行封装 不同为默认值
- @RequestMapping(value = "/test12")
- //注意这个如果请求参数没有输入 user和role对象是不为空 只是它们的属性为默认值----优点:我们不需要进行判断是否为空
- public String test12(User user ,Role role ,ModelAndView model) {
- return "/test.jsp";
- }
注意:
如果请求参数和形参中所有的属性名都不一致,自定义类型的属性不为null,但是成员变量都为默认值
即 上面例子中 user 和role 对象不为null 但是它们两个的成员变量为默认值
类似于 request.getParameterValues("属性名")
将同名的请求参数封装为数组,并自动进行类型转换。
在形参列表中定义一个数组类型的参数
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="ISO-8859-1">
- <title>Insert title heretitle>
- head>
- <body>
- <form action="a/test13" method="post">
- <input type="checkbox" name="ids" value="1">1
- <input type="checkbox" name="ids" value="2">2
- <input type="checkbox" name="ids" value="3">3
- <input type="checkbox" name="ids" value="4">4
- <input type="checkbox" name="ids" value="5">5
- <input type="checkbox" name="ids" value="6">6
- <input type="submit" value="提交">
- form>
- body>
- html>
- @RequestMapping(value = "/test13" ,method = RequestMethod.POST)
- public String test13(Integer[] ids) {
- for (Integer integer : ids) {
- System.out.println(integer);
- }
- return "/test.jsp";
- }
- @RequestMapping(value = "/test13" ,method = RequestMethod.POST)
- public String test13(@RequestParam(name="ids") Integer[] idss) {
- for (Integer integer : ids) {
- System.out.println(integer);
- }
- return "/test.jsp";
- }
作用将请求参数封装为扩展类,主要用于复杂表单的构建(动态表单)
将扩展类做为形参的参数


- package com.sofwin.pojo;
-
- import java.util.Date;
- import java.util.List;
-
- import org.springframework.format.annotation.DateTimeFormat;
-
- import com.fasterxml.jackson.annotation.JsonIgnore;
- import com.fasterxml.jackson.annotation.JsonProperty;
-
- public class User {
- private Integer id;
- // @JsonIgnore //忽略系列化
- @JsonProperty(value = "name") //修改序列化字段 即 返回的就是name=。。。。
- private String userName ;
- private Integer userAge;
- // @DateTimeFormat(pattern = "yyyy.MM.ss")
- private Date date;
-
- public Date getDate() {
- return date;
- }
- public void setDate(Date date) {
- this.date = date;
- }
- private List
roles; -
- public List
getRoles() { - return roles;
- }
- public void setRoles(List
roles) { - this.roles = roles;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public Integer getUserAge() {
- return userAge;
- }
- public void setUserAge(Integer userAge) {
- this.userAge = userAge;
- }
-
-
-
-
-
-
- }
- package com.sofwin.pojo;
-
- public class Role {
- private Integer id;
- private String roleName ;
- private Integer roleAge;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getRoleName() {
- return roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
- public Integer getRoleAge() {
- return roleAge;
- }
- public void setRoleAge(Integer roleAge) {
- this.roleAge = roleAge;
- }
-
-
-
-
-
- }
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title heretitle>
- head>
- <body>
- <div><h1>用户数据h1>div>
- <div>
- <form action="a/test14" method="post">
- <div>用户名称<input type="text" name="userName" /> 用户年龄<input type="text" name="userAge" />div>
- <div style="float:right"> <input type="button" onclick="addRole()" value="增加权限"/>div>
- <div id="roleDate">div>
- <div><input type="submit" value="保存"/>div>
- form>
- div>
- body>
-
-
- <script type="text/javascript">
- var index=0; //设置索引
- function addRole() {
- var info=document.getElementById("roleDate").innerHTML;
- info+='
角色名称'].roleName"/>' - document.getElementById("roleDate").innerHTML=info;
- index++;
- }
-
- script>
- html>
- //集合
- @RequestMapping(value = "/test14" ,method = RequestMethod.POST)
- public String test14(User user) {
-
- return "/test.jsp";
- }
集合请求参数的名称为 集合的属性的属性名[索引].属性名
即例子中的 roles[0].roleName
中文乱码,我们是设置编码是UTF-8,在之前的web我们是自己创建的过滤器对所有的请求进行过滤,进行编码的设置
springmvc给我们提供了过滤器,我们直接使用即可
提过的过滤器是在spring-web的jar包中的一个类




在web.xml中设置
-
- <filter>
- <filter-name>postEncodingfilter-name>
-
- <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
- <init-param>
-
- <param-name>encodingparam-name>
- <param-value>UTF-8param-value>
- init-param>
- <init-param>
-
- <param-name>forceRequestEncodingparam-name>
- <param-value>trueparam-value>
- init-param>
- <init-param>
-
- <param-name>forceResponseEncodingparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>postEncodingfilter-name>
-
- <url-pattern>/*url-pattern>
- filter-mapping>
这样设置就可以解决中文乱码的问题
springmvc提供了内置的类型转换器
其中Date 是yyyy/MM/ss 但是其他的例如-或者.都是不行的 ,因此我们可以自定义设置
开启mvc的注解驱动(要引入mvc的约束)
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- https://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/aop
- https://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/mvc
- https://www.springframework.org/schema/mvc/spring-mvc.xsd
-
- ">
-
-
- <context:component-scan base-package="com.sofwin">context:component-scan>
-
-
-
- <mvc:annotation-driven>mvc:annotation-driven>
-
- beans>
使用@DateTimeFormat(pattern="yyyy-MM-dd")

- @RequestMapping(value = "/test15" )
- public String test15(User user) {
-
- return "/test.jsp";
- }
这样设置完毕后 请求参数是String,就会自动转换为date类型
- package com.sofwin.converter;
-
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.logging.SimpleFormatter;
-
- import org.springframework.core.convert.converter.Converter;
-
-
- // s代表的传入参数的类型 T 表示要转换的类型
- public class MyDateConverter implements Converter
{ -
- @Override
- public Date convert(String date) {
- SimpleDateFormat sdf=new SimpleDateFormat("yyyy=MM=ss");
- try {
- Date flag = sdf.parse(date);
- return flag;
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-
- }
- <bean id="myDateConverter" class="com.sofwin.converter.MyDateConverter">bean>
- <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
- <property name="converters">
- <set>
-
- <ref bean="myDateConverter"/>
- set>
- property>
- bean>
mvc:annotation-driven conversion-service="conversionServiceFactoryBean">mvc:annotation-driven>
测试
- @RequestMapping(value = "/test16" )
- public String test16(Date date) {
- return "/test.jsp";
- }



因为在这个xml中设置了/ 代表处理jsp其他都要进入到前端控制器,但是在前端控制器中找不到js的映射 因此会无法使用js 或者是css image等
因此我们要设置让这些的静态资源不进入到前端控制器中
-
- <mvc:resources location="/css/" mapping="/css/**">mvc:resources>
- <mvc:resources location="/js/" mapping="/js/**">mvc:resources>
<mvc:default-servlet-handler />
@RestController
类级别的组合注解
就相当于两个注解的组合
@Controller 和@ResponseBody
这两个注解的意义: 声明该类的所有请求都是异步请求
同步请求和异步请求两者之间的区别
同步请求是返回的视图
异步请求是返回的数据
springmvc默认支持的异步请求中数据的格式转换jackson,来将数据序列化为json格式
json格式要添加的三个依赖
jackson-core
jackson-databind
jackson-annotation
- //1.无返回值
- //@ResponseBody 声明这个方法是异步请求
- //同步请求 返回的是视图 异步请求返回的数据 可以是json 可以是字符串 等等
- @ResponseBody
- @GetMapping("/test01")
- public void test01(HttpServletResponse response) throws IOException {
- PrintWriter writer = response.getWriter();
-
- writer.write("/test01/jsp");
- }
结果是

- //2.返回String
- @ResponseBody
- @GetMapping("/test02")
- public String test02() {
- return "王五";
- }
- //3.返回自定义类型 异步请求返回的是json对象,springmvc根据jackson将结果自动进行json序列化
- //这里要放三个json-jar包 jsckson-core jsckson-databind jsckson-annotations
- @ResponseBody
- @GetMapping("/test03")
- public User test03(User user) {
- return user;
- }
- //4.返回集合
- @ResponseBody
- @GetMapping("/test04")
- public List
test04() { - List list =new ArrayList();
- for(int i=1;i<100;i++) {
- User user =new User();
- user.setId(i);
- user.setUserName("sofwin"+i);
- list.add(user);
- }
- return list;
- }
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <script src="js/jquery-3.6.0.js">script>
- <link rel="stylesheet" href="css/css1.css">
- <title>Insert title heretitle>
- head>
- <body>
- <input type="button" onclick="bind()" value="异步请求"/>
-
-
- body>
- <script type="text/javascript">
- function bind() {
- $.ajax({
- url:"test06?UserName=zhangsan&userAge=11",
- type:"post",
- dataType:"json",
- success:function(ret){
- alert(ret);
- //JSON要大写
- alert(JSON.stringify(ret));
- $.ajax({
- url:"test07",
- type:"post",
- data:JSON.stringify(ret),
- dataType:"json",
- contentType:"application/json",
- success:function(ret){
- alert(JSON.stringify(ret));
- }
- })
- }
- })
- }
-
- script>
- html>
- @ResponseBody
- @PostMapping("/test06")
- public User test06( User user) {
- return user;
- }
-
-
- @ResponseBody
- @PostMapping("/test07")
- public User test07(@RequestBody User user) {
- return user;
- }
实例


@JsonLgnore 忽略序列化

这样设置就不会显示username了
- @ResponseBody
- @GetMapping("/test03")
- public User test03(User user) {
- return user;
- }

@JsonProperty 修改序列化字段的名称

- @ResponseBody
- @GetMapping("/test03")
- public User test03(User user) {
- return user;
- }

RESTFUL 是一种网络应用程序的设计风格和开发方式,基于 HTTP ,可以使用 XML 格式定义或 JSON 格式定义。 RESTFUL 适用于移动互联网厂商作为业务接口的场景,实现第三方 OTT 调用移动网络资源的功能,动作类型为新增、变更、删除所调用资源
@PathVariable
用于声明路径变量,是一个参数级别的注解,接受请求参数,并将接受请求参数作为请求地址
- //Resful风格
- @ResponseBody
- @GetMapping("/info/{name}")
- public String test07(@PathVariable String name) {
- return name;
- }
输入wentao ,页面返回wentao

输入zhangsan ,页面返回zhangsan
