1. 程式人生 > >springboot學習(2)-編寫後端介面(2種方式)

springboot學習(2)-編寫後端介面(2種方式)

可以將啟動類和controller放一起,如下:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @RequestMapping("/")
    String index(){
        return "index";
    }
}

寫後端介面的兩種方式:

1.類上加@RestController註解:

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class WebController {

    @RequestMapping(value="/api",method = RequestMethod.GET)
    public Map<String, Object> api(){
    Map<String , Object> result = new HashMap<String , Object>();
    result.put("Code","200");
    result.put("Msg","成功");
    return result;
}
}

2.類上加@Controller註解,介面上加@ResponseBody註解:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebController {
    @ResponseBody
    @RequestMapping(value="/api",method = RequestMethod.GET)
    public Map<String, Object> api(){
    Map<String , Object> result = new HashMap<String , Object>();
    result.put("Code","200");
    result.put("Msg","成功");
    return result;
}
}