Serving Web使用Spring MVC

来源:互联网 发布:开淘宝店的账怎么做账 编辑:程序博客网 时间:2024/06/05 03:28
在spring构建web网站的方法中,HTTP请求被控制器处理。你通过@Controller注解,可以很容易的识别
request请求。
import java.util.concurrent.atomic.AtomicLong;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class GreetingController {    private static final String template = "Hello, %s!";    private final AtomicLong counter = new AtomicLong();    @RequestMapping("/greeting")    public @ResponseBody Greeting greeting(            @RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {        return new Greeting(counter.incrementAndGet(),                            String.format(template, name));    }@RequestMapping注解保证了HTTP请求/greeting和greeting()方法映射。注意,上面的例子没有确定是GET,或PUT,或POST请求,因为@RequestMapping
默认的匹配所有的http请求。@RequestParam 绑定了查询的字符串参数“name”的值到greeting()方法中的参数name。这个字符串参数不是必需的,如果request请求中没有那个值,那么它的默认值为“World”.name参数的值被添加到Model对象
上,最后可以访问到视图模板。
0 0
原创粉丝点击