Spring:基於註解的MVC程序示例

控制層(C)

首先建立一個controllerhtml

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", defaultValue="world")String name, Model model){
        model.addAttribute("name", name);
        return "index";
    }
}

@Controller註解標註這個類是一個控制類;java

@RequestMapping("/greeting")註解映射/greeting訪問到此方法;web

@RequestParam(value="name", defaultValue="world")註解將請求中的name參數傳遞給變量,若無取默認值;spring

model 對象添加的屬性能夠從前臺取到;瀏覽器

return 返回的值即爲此controller綁定的頁面名。app

視圖層(V)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

啓動應用程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

而後瀏覽器訪問: http://localhost:8080/greeting?name=Johnsvg

相關文章
相關標籤/搜索