基于注解的SpringMVC

SpringMVC基于注解的请求

     在使用SpringMVC注解前,首先要启用注解,在springMVC3.x版本之后提供了非常简单的启用注解方法只需要的-servlet.xml中加上<mvc:annotation-driven/>另外还需要告诉应用程序哪些包使用注解,在-servlet.xml中加入<context:component-scanbase-package="controller"/>说明controller包中使用注解,那么在启动应用程序时,就会自动扫描controller中的注解,找到请求映射与之对应的controller和处理方法。

在请求映射中主要使用@Controller注解和@RequestMapp注解,@Controller注解一个类,说明该类是一个Controller,@RequestMapping注解方法,含有映射名参数,该参数指定映射对应的处理方法。例如:

Login.jsp

<formaction="login"method="">

    username:<inputtype="text"name="name"/><br/>

    password:<inputtype="password"name="password"/><br/>

    <inputtype="submit"value="login"/>

</form>

 

LoginController.java

@Controller

publicclassLoginController {

 

    @RequestMapping("/login")

   public ModelAndViewlogin(HttpServletRequest request,HttpServletResponse response)

   {

      System.out.println("-------------");

       

      returnnewModelAndView("ok");

   } 

}

 

 

-servlet.xml

<mvc:annotation-driven/>

      <context:component-scanbase-package="controller"/>

      <beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">

         <propertyname="prefix"value="/"/>

         <propertyname="suffix"value=".jsp"/>

      </bean>

     

 

 

   在@RequestMapping中另外两个参数method和param,method有requestMethod.POST、requestMethod.GET等值,表示请求的方式,例如在上例中@RequestMapping(value=”/login”,method=requestMethod.PST)就表示该方法处理的请求必须是post的请求方法,那么此时在form表单中method=“post”

param的值是一个String数组,说明请求中必须包含哪些请求参数,例如@RequestMapping(value=”login”,param={“name”,”password”})说明请求中必须包含name和password两个参数,才用该方法处理。

 

@RequestMapping不仅可以注解方法,还可以注解类,注解类一般用于多方法的处理器中,例如在上例中使用@RequestMapping(“/user”)注解LoginController类,那么此时form表单中action中值改为“user/login”才能将请求传递给login方法.

在请求中路径中,不加“/”表示的是绝对的路径,加“/”表示的是相对当前资源的路径。

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值