@Controller和@RequestMapping和@RequestParam注解理解和区别

    在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,
然后再把该Model 返回给对应的View 进行展示。在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,
只需使用@Controller 标记一个类是Controller ,
然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到

 @Controller 

   用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 类。需要在springmvc中进行配置,告诉Spring 该到哪里去找标记为@Controller 的Controller 控制器。

    < context:component-scan base-package = "com.host.app.web.controller" >
       < context:exclude-filter type = "annotation"
           expression = "org.springframework.stereotype.Service" />
    </ context:component-scan > 

@RequestMapping

  映射 Request 请求与处理器,可以定义在类上,也可以定义在方法上。如果定义在类上,访问的就是相对路径,相对于类而言。如果定义在方法上,相对于方法的映射而言

@Controller
@RequestMapping("/main")
public class MainController {
    
    @RequestMapping(value="index")
    public String index(HttpSession session) {
        session.invalidate();
        return "index";
    }

@RequestParam

当需要从request 中绑定的参数和方法的参数名不相同的时候,也需要在@RequestParam 中明确指出是要绑定哪个参数。在@RequestParam 中除了指定绑定哪个参数的属性value 之外,还有一个属性required ,它表示所指定的参数是否必须在request 属性中存在,默认是true ,表示必须存在,当不存在时就会报错。

   @RequestMapping ( "requestParam" )
   public String testRequestParam( @RequestParam(required=false) String name, @RequestParam ( "age" ) int age) {
       return "requestParam" ;
    } 

其他更多详细的注解https://www.cnblogs.com/jpfss/p/8047628.html

 

posted @ 2019-06-20 20:59  旺旺a  阅读(4056)  评论(0编辑  收藏  举报