1. 程式人生 > >【springboot】2、Controller和引數

【springboot】2、Controller和引數

類上的配置

@RestController
public class SpringdemoApplication {
    ...
}

其中@RestController表示返回string或者json內容(即直接返回內容),而如果是@Controller則表示可以返回一個跳轉的頁面(jsp或者html)

想在一個類中既能返回string或者json又能進行頁面跳轉怎麼辦?

其實@RestController = @Controller + @ResponseBody。

所以,以後定義controller的時候,可以直接使用@Controller,如果需要返回json可以直接在方法中新增@ResponseBody即可。

@SpringBootApplication
@Controller
public class SpringdemoApplication {

    @RequestMapping("/")
    @ResponseBody
    public String greeting() {
        return "Hello World!";
    }

    // 可變子路徑,訪問時http://127.0.0.1:8080/users/hello對應引數username的值就是hello
    // URL中的變數可以用{variableName}來表示,同時在方法的引數中加上
    // @PathVariable("variableName"),那麼當請求被轉發給該方法處理時,
    // 對應的URL中的變數會被自動賦值給被@PathVariable註解的引數
    @RequestMapping("/users/{username}")
    @ResponseBody
    public String userProfile(@PathVariable("username") String username) {
        return String.format("user %s", username);
    }

    // 設定請求方式
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public String loginGet() {
        return "Login Get Page";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String loginPost() {
        return "Login Post Request";
    }

    // 返回Html頁面
    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name, Model model) {
        model.addAttribute("name", name); // 設定引數
        return "hello";
        // 返回hello表示尋找名字為hello的模板進行渲染
        // Thymeleaf模板引擎進行模板渲染需要引入spring-boot-starter-thymeleaf
        // 預設的模板資料夾src/main/resources/templates/目錄下新增一個模板檔案hello.html
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringdemoApplication.class, args);
    }
}

專案中多個Controller

專案中如果針對不同的業務劃分不同的Controller,則可以直接在不同的類上使用@Controller或者@RestController即可  工程結構如下: 這裡寫圖片描述

注意Html頁面要放在src\main\resources\templates\資料夾下

如:新增一個RestController返回string/json

@RestController
public class NomalController {
    ...
    @RequestMapping("/test")
    public String testParam(String name, String psw) {
        return name + " | " + psw;
    }
}

新增一個可以返回Thymeleaf模板引擎渲染的Html頁面

@Controller
public class WebController {
    ...
    @RequestMapping("/testHtml")
    public String test(ModelMap model,String name,String psw){
        model.addAttribute("name", name);
        return "test";
    }
}

注意:Thymeleaf模板渲染需要在pom.xml中新增依賴

<!-- Thymeleaf模板引擎,渲染Html頁面 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

此時Application中可以不用做Controller的處理,作為一個普通的入口即可

@SpringBootApplication
public class SpringdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringdemoApplication.class, args);
    }
}

請求中的引數處理

返回內容是string或者json

@RequestMapping("/test")
@ResponseBody
public String testParam(String name,String psw){
    return name+" | "+psw;
}

這裡的引數名和客戶端請求的引數名一致,客戶端請求如:

    http://127.0.0.1:8080/test?name=abc&psw=123

如果請求結果是跳轉到某個jsp/html頁面,則可以藉助Model/ModelMap傳遞引數,其中:

Model是包含四個addAttribute 和一個  merAttribute方法的介面。
ModelMap是實現了Map介面,包含Map方法。檢視層通過request找到ModelMap中的資料
ModelAndView:是包含ModelMap和檢視物件的容器。既包含模型也包含檢視,而ModelMap只是包含模型的資訊。

ModelMap/Model物件主要用於傳遞控制方法傳遞資料到結果頁面。類似於request的setAttribute方法的作用。

所以我們要想在jsp頁面獲取資料,只要將資料放到ModelMap物件中即可。如都將引數name以及psw的值傳遞到login.hml頁面,表示如下(2種方式)

    @RequestMapping("/testLogin")
    public ModelAndView testModel(String name, String psw) {
        ModelAndView model = new ModelAndView("login");
        model.getModelMap().addAttribute("name", name);
        model.getModelMap().addAttribute("psw", psw);
        return model;
    }

    @RequestMapping("/testLogin1")
    public String testModel(ModelMap model,String name,String psw){
        model.addAttribute("name", name);
        model.addAttribute("psw", psw);
        return "login";
    }

建議所有的引數都用包裝型別,別用原始型別,原始型別如果不傳的話為null,如:引數是int型別那麼不傳引數會收到null,然而null無法轉為int會出現異常

在Html頁面上可以直接通過${model引數名}獲取引數

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>LoginTest</title>
</head>
<body>
    <h1>LoginTest</h1>
    <p th:text="'name=' + ${name} + ' and psw='+${psw}" />
</body>
</html>

當前的工程結構: 這裡寫圖片描述 執行效果: 這裡寫圖片描述

這裡寫圖片描述