天天看点

SpringMVC之控制器@Controller和@RequestMapping

控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。

控制器负责解析用户的请求并将其转换为一个模型。

实现接口的Controller:

实现接口Controller定义控制器是较老的办法

缺点是:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦,一般用不到。

1.编写一个r类,ControllerTest1实现Controller接口:

//定义控制器
//注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       //返回一个模型视图对象
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","Test1Controller");
       mv.setViewName("test");
       return mv;
  }
}
           

2.编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类

3.编写前端test.jsp

注解实现Controller:

@Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还提到了另外3个注解)

1.Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.controller"/>
           

2.增加一个ControllerTest2类,使用注解实现;

//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2{

   //映射访问路径
   @RequestMapping("/t2")
   public String index(Model model){
       //Spring MVC会自动实例化一个Model对象用于向视图中传值
       model.addAttribute("msg", "ControllerTest2");
       //返回视图位置
       return "test";
  }
}
           

@RequestMapping

@RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。先拼接类上的父路径,再拼接方法上的子路径。

例如:http://localhost:8080 / 项目名/ admin /h1

@Controller
@RequestMapping("/admin")
public class TestController {
   @RequestMapping("/h1")
   public String test(){
       return "test";
  }
}