码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC(二):基于注解的SpringMVC入门

时间:2015-09-12 14:53:53      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

1、使用注解时需要注意xml的配置

    <mvc:annotation-driven />

  • 对包进行扫描,实现注释驱动Bean定义,同时将bean自动注入容器中使用。即解决了@Controller标识的类的bean的注入和使用。

  • 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean。

  • 如果没有<mvc:annotation-driven/>,那么所有的Controller可能就没有解析,没有相应的Controller就会被default servlet处理。


    <context:component-scan base-package="用于扫描的包" />

  • 启用自动检测


2、@Controller

    标识一个控制器


3、@RequestMapping

  • 在类级别上则表示相对路径

  • 在方法级别上则表示访问路径

@RequestMapping的value值前后是否有“/”对请求的路径没有影响,即value="test" 、"/test"、"/test/"其效果是一样的


例如:http://localhost:8080/MySpringMVC/roger/test  访问showTest()

@Controller
@RequestMapping("/roger")
public class TestController {
    @RequestMapping("/")
    public String showIndex() {
        return "index";
    }

    @RequestMapping(value="/test")
    public String showTest() {
        return "test";
    }


@RequestMapping(params="action=del"),请求参数包含“action=del",如http://localhost:8080/MySpringMVC/roger/test?action=del  


4、@RequestParam()

    使用@RequestParam("xx")注解获取GET请求或POST请求提交的参数,替代request.getParameter("xx")

例如:

    访问链接:http://localhost:8080/MySpringMVC/roger/testParam?username=roger

@RequestMapping(value = "/testParam", method = RequestMethod.GET)
  public String testParam(HttpServletRequest request, @RequestParam("username") String username) {
    System.out.println("HttpServletRequest, username:" + request.getParameter("username"));
    System.out.println("@RequestParam(), username:" + username);
    return "test";
}


5、@PathVariable

    使用@PathVariable注解提取路径中的变量值

例如:

@RequestMapping(value = "/testPathVariable/{username}", method = RequestMethod.GET)
public String testPathVariable(@PathVariable String username) {
    System.out.println("username:" + username);
    return "test";
}

访问路径可以是:http://localhost:8080/MySpringMVC/roger/testPathVariable/roger_fang

但是/testPathVariable/{username},路径中username部分不能有‘/‘。



SpringMVC(二):基于注解的SpringMVC入门

标签:

原文地址:http://my.oschina.net/u/1020238/blog/505274

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!