spring mvc 入门案例

去学习了下spring MVC的官网例子,使用起来真方便了许多,主要步骤如下:

1,首先要,创建一个Web容器:

package hello;

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注解指明该类是一个web容器类
//是可以被ComponentScan 扫描到的,是一种Component类型
//这个类就相当servlet
@Controller
public class GreetingController {
//接收的url映射地址
@RequestMapping("/greeting")
//@RequestParam 需要传递的参数'name',但是非必须,默认情况下值为world
//跳转到'greeting'的视图,就是greeting.html
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
 

 
如果想指定接受http action类型,可以设置@RequestMapping(method=GET)

2,视图创建src/main/resources/templates/greeting.html
官网说明视图类型可以有很多种,
http://spring.io/understanding/view-templates
而这里使用的是Thymeleaf模板,具体模板用法可以参考http://www.thymeleaf.org/

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

 

3,执行类src/main/java/hello/Application.java

package hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

//让spring递归的去扫描package hello下面所有的class文件,如果被标记@Componnet则被spring管理
@ComponentScan
//spring会做一些默认的操作,比如Application类会依赖嵌入式的tomcat,则tomcat会启动和配置
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        //spring会去管理该类,并且去读取application中的注解的内容
        SpringApplication.run(Application.class, args);
    }
}

 

4,运行
在gs-serving-web-content-master/complete/路径下运行  gradlew build
java -jar build/libs/gs-serving-web-content-0.1.0.jar

在浏览器中输入http://localhost:8080/greeting
或者http://localhost:8080/greeting?name=User 可以看到效果。

猜你喜欢

转载自betakoli.iteye.com/blog/2111876