补充:springMVC获取数据格式|getpost乱码解决|rest风格

SpringMVC 注解方式实现JSON数据转换

步骤一:导入JSON转换的jar包

<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.9.3</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.9.3</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-annotations</artifactId>
 <version>2.9.3</version>
</dependency>

步骤二:创建一个控制器类,并填入数据

package com.wolfcode.handler;

import com.wolfcode.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
public class SecondHandler {

   @ResponseBody
   @RequestMapping("/json.zt")
   public Object getJson(){
       HashMap<Object, Object> map = new HashMap<>();
       map.put("code","200");
       map.put("msg","请求成功");
       Student student = new Student();
       student.setsName("你");
       student.setAge(2);
       student.setSex('男');
       map.put("data",student);
       return map;
  }
}

@Controller 需要添加扫描器 context

@ResponseBody 需要添加扫描器生效 mvc 作用:让这个方法自动执行JSON转换

@RequestMapping("/json.zt") :接口访问路径

步骤三:在applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"

      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <mvc:annotation-driven></mvc:annotation-driven>

   <context:component-scan base-package="com.wolfcode"></context:component-scan>
</beans>

执行运行:

image-20220412133026532

SpringMVC之GET和POST请求

  1. get请求

    • 请求的数据为简单数据类型

      • 页面

        <form action="/getreq.zt" method="get">
          姓名:<input type="text" name="uname"><br>
          密码:<input type="password" name="upassword">
           <input type="submit" value="提交">
        </form>
      • controller

        @ResponseBody
        @RequestMapping("/getreq.zt")
        public Map<String,Object> getreq (String uname,String upassword){
           System.out.println(uname+"---"+upassword);
           HashMap<String, Object> map = new HashMap<>();
           map.put("uname",uname);
           map.put("upassword",upassword);
           return map;
        }
      • 请求成功

        image-20220412133105814

        image-20220412133120543

    • 接受的数据类型为复杂数据类型比如一个数组

      • 页面

        <form action="/getreq2.zt" method="get">
          打游戏:<input type="checkbox" name="hobby" value="打游戏">
          耍游戏:<input type="checkbox" name="hobby" value="耍游戏">
          看游戏:<input type="checkbox" name="hobby" value="看游戏">
           <input type="submit" value="提交">
        </form>
      • controller

        @ResponseBody
        @RequestMapping("/getreq2.zt")
        public Map<String,Object> getreq(String[] hobby){
           HashMap<String, Object> map = new HashMap<>();
           map.put("hobbies", Arrays.toString(hobby));
           System.out.println(Arrays.toString(hobby));
           return map;
        }
      • 请求成功

        image-20220412133137550

        image-20220412133150792

        数据获取成功,只是出现乱码问题,后面回去解决

    • 如果需要传入较多的参数时,我们可以将其封装成一个实体类,在传参时传入这个对象即可

      • 页面

        <form action="/getreq3.zt" method="get">
          姓名:<input type="text" name="uname"><br>
          密码:<input type="password" name="upassword">
          电话:<input type="text" name="phone"><br>
          地址:<input type="text" name="address">
           <input type="submit" value="提交">
        </form>
      • 实体类

        <!--       简化bean代码的工具包-->
               <dependency>
                   <groupId>org.projectlombok</groupId>
                   <artifactId>lombok</artifactId>
                   <optional>true</optional>
                   <version>1.18.4</version>
               </dependency>

        使用lombok工具进行简化我们的实体类

        package com.wolfcode.entity;

        //使用@Data可以帮助我们完成getset以及toString的方法
        @Data
        //可以帮我们完成构造无参构造的方法
        @NoArgsConstructor
        //完成有参构造方法的注入
        @AllArgsConstructor
        public class Register {

           private String uname;
           private String upassword;
           private String phone;
           private String address;
        }
      • controller

        @ResponseBody
        @RequestMapping("/getreq3.zt")
        public Map<String,Object> getreq(Register register){
           HashMap<String, Object> map = new HashMap<>();
           map.put("data",register);
           System.out.println(register);
           return map;
        }
      • 请求成功

        image-20220412133256769

        image-20220412133308666

注意:

  1. 页面数据参数的name属性需要和controller里面参数名一致

  2. 如果页面参数的name属性太长,后端人员不想用前端给的参数名,可以使用注解@RequestParam("前端页面name属性值") 参数类型 参数的方式来实现,但是一个注解只能对应一个参数,比如

    页面:

    <form action="/getreq.zt" method="get">
      姓名:<input type="text" name="utudedadsantname"><br>
      密码:<input type="password" name="dadadaadupassword">
       <input type="submit" value="提交">
    </form>

    controller:

    @ResponseBody
    @RequestMapping("/getreq.zt")
    public Map<String,Object> getreq (@RequestParam("utudedadsantname") String uname, @RequestParam("dadadaadupassword") String upassword){
       System.out.println(uname+"---"+upassword);
       HashMap<String, Object> map = new HashMap<>();
       map.put("uname",uname);
       map.put("upassword",upassword);
       return map;
    }

    请求成功:

    image-20220412133434470

    image-20220412133446590

  1. post请求

只需要将method修改为post就可以了,效果与get差不多,只不过请求头上没有了数据

页面:

<form action="/getreq3.zt" method="post">
  姓名:<input type="text" name="uname"><br>
  密码:<input type="password" name="upassword">
  电话:<input type="text" name="phone"><br>
  地址:<input type="text" name="address">
   <input type="submit" value="提交">
</form>

controller:

@ResponseBody
@RequestMapping("/getreq3.zt")
public Map<String,Object> getreq(Register register){
   HashMap<String, Object> map = new HashMap<>();
   map.put("data",register);
   System.out.println(register);
   return map;
}

请求成功:

image-20220412140219311

image-20220412140231743

SpringMVC之GET和POST请求解决乱码的方法

如果在发送请求的时候使用到了中文,可能会出现乱码的问题(上面就有的情况是这样的)

  1. 解决get请求乱码问题

    找到pom.xml文件,找到Tomcat插件配置

    <build>
       <plugins>
         <plugin>
           <groupId>org.apache.tomcat.maven</groupId>
           <artifactId>tomcat7-maven-plugin</artifactId>
           <version>2.2</version>
           <configuration>
             <path>/</path>
             <port>8080</port>
               
    <!--         解决get请求乱码-->
             <uriEncoding>UTF-8</uriEncoding>
               
           </configuration>
         </plugin>
       </plugins>
     </build>

    运行结果

    image-20220412140255877

    image-20220412140428398

  2. 解决post请求乱码问题

    找到web.xml文件,配置解决post请求乱码问题

    <filter>
     <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
     <url-pattern>/*</url-pattern>
    </filter-mapping>

    运行结果

    image-20220412140531067

  3. 同时解决get和post请求乱码问题(原理)

    页面:

    <form action="/getreq3.zt" method="post">
      姓名:<input type="text" name="uname"><br>
      密码:<input type="password" name="upassword">
      电话:<input type="text" name="phone"><br>
      地址:<input type="text" name="address">
       <input type="submit" value="提交">
    </form>
    <form action="/getreq3.zt" method="get">
      姓名:<input type="text" name="uname"><br>
      密码:<input type="password" name="upassword">
      电话:<input type="text" name="phone"><br>
      地址:<input type="text" name="address">
       <input type="submit" value="提交">
    </form>

    controller:

    @ResponseBody
    @RequestMapping("/getreq3.zt")
    public Map<String,Object> getreq(Register register){
       System.out.println("乱码:"+register);
       //1.获取到乱码前实体类里面的乱码数据
       String uname = register.getUname();
       String address = register.getAddress();
       //2.获取到后将其原先的ISO-8859-1的编码方式转化为utf-8的编码方式,再将转变好的utf-8存入到register对象中
       try {
           byte[] unameBytes = uname.getBytes("ISO-8859-1");
           uname= new String(unameBytes, "utf-8");
           register.setUname(uname);
           byte[] addressBytes = address.getBytes("ISO-8859-1");
           address = new String(addressBytes, "utf-8");
           register.setAddress(address);
      } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
      }
       //3.最后返回
       HashMap<String, Object> map = new HashMap<>();
       map.put("data",register);
       return map;
    }

    测试结果:

    image-20220412140709212

    image-20220412140716998

     

    注意:在解决字符编码问题时,只能存在一个处理方法,如果一个项目中存在多个解决字符编码的问题的话,可能就不会起作用。

    同时解决get和post请求乱码的问题的思路

    1. 调用对象的get方法获取到乱码的数据

    2. 调用乱码数据的getBytes("ISO-8859-1")方法获取到它乱码时字符编码的字节数组

    3. 然后调用new String()方法,第一个参数填入目标字节数组,第二个参数填入utf-8编码规则

    4. 最后将编码正确的数据重新set到对象中就可以了

 

补充:restful风格

restful的使用:在进行表现层中的行为有

  • GetMapping 查询

  • PostMapping 添加

  • PutMapping 修改

  • DeletMapping 删除

以查询为例:

在Controller层:

@RequestMapping("/bks")
public class bookController1 {
    @GetMapping
public List<Book> all(){
// List<Book> list = bookService.allList();
List<Book> list = bookService.list();
return list;
}
}

我们在前端页面使用axios:

getAll() {
//  验证前端是否响应
// console.log("来咯..")
// 发送异步请求
// 进行提升作用域
var _this=this;
axios.get("/bks").then((res)=>{
//注意在获取后端的数据时
// 我们要明白res.data和res.data.data
// console.log(res.data.data);
_this.dataList=res.data.data
})
},

其中

axios.get("/bks")

就表示从我们的Controller中找到/bks路径下关于get请求的的方法。

 

posted @ 2022-04-14 14:50  孤巷一人i  阅读(77)  评论(0)    收藏  举报