欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

1503—SpringMVC建立webAPI

程序员文章站 2022-03-10 20:37:44
一、基本用法 1—字符串组装 @RestController@RequestMapping("/api/Student")public class StudentController { @RequestMapping(value ="/webapi.do",produces = "text/plain;charset=UTF-8",method = RequestMethod.GET) public String getOne()......

一、基本用法 

       1—字符串组装        

@RestController
@RequestMapping("/api/Student")
public class StudentController {

        @RequestMapping(value ="/webapi.do",produces = "text/plain;charset=UTF-8",method = RequestMethod.GET)
        public String getOne(){

            StringBuilder  result=new StringBuilder();
            result.append("{\"Success\":\""+"true"+"\",");
            result.append("\"Message\":\""+"第一次测试webApI,返回结果"+"\"");
            result.append("}");

            return result.toString();
        }
}

     说明:@requestMapping注解中的produces属性取值为response的编码值(解决前端显示乱码)

     2—对象转换json

     pom.xml引入jackson依赖     

     jackson和springMVC框架匹配度有要求,不匹配则报BeanInstanceException错误。

<!--   对应于springMVC框架5.0以上版本         -->
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
</dependency>
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
</dependency>

     控制器方法

@RequestMapping(value ="/two.do",produces = "text/plain;charset=UTF-8",method = RequestMethod.GET)
public String getTwo() throws JsonProcessingException {
    //1——ajaxResult为返回结果类对象
     ajaxResult result =new ajaxResult();
     result.setSuccess(true);
     result.setMessage("不确认能不能显示中文");
    //2——转化对象为String
        ObjectMapper  jsonHandler=new ObjectMapper();
        String strRes = jsonHandler.writeValueAsString(result);
        System.out.println("值====================="+strRes);

        return strRes;
}

     说明:依然需要@requestMapping的produces属性进行编码设定。

     3—POST方法另一种写法

@PostMapping(value = "/three.do",produces = "text/plain;charset=UTF-8")
public String getThree( @RequestParam( value = "username",required = true)  String name, @RequestParam(value = "address")   String Address) throws JsonProcessingException {

        ajaxResult result =new ajaxResult();
        result.setSuccess(true);
        result.setMessage("处理后结果  [ "+name+" ]/ " +Address);

        ObjectMapper  jsonHandler=new ObjectMapper();
        String strRes = jsonHandler.writeValueAsString(result);
        return strRes;
}

 

 

 

 

本文地址:https://blog.csdn.net/zhang_yling/article/details/112008068