基于注解的SpringMVC
基于注解的话,需要添加几个配置内容到 springmvc-servlet.xml文件中(这个文件使我们配置的spring配置文件,在web.xml中配置的)
基于注解的方式,可能不仅仅依赖与DefaultAnnotationHandlerMapping,
但我们还需要添加一句:<mvc:annotation-driven/>
他提供了SpringMVC注解的所有支持,以及JSR-303的注解支持。
这里的类是支持注解的。import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class QueryController { @RequestMapping("/index.htm") public void requestIndexHtml(HttpServletRequest request, HttpServletResponse respose){ } }
注:如果不用@Controller 注解,需要自己定义这个bean,
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/home") public class QueryController { @RequestMapping({"/default.htm","/index.htm"}) public void requestIndexHtml(HttpServletRequest request, HttpServletResponse respose, @RequestParam(required = true) int days, @RequestParam(required = true) String key){ //Add you code } }
(1)请求中的参数 days 和 key输入不能为空(required = true 表示参数不能为空)
如果没有@RequestParam ,默认情况下 required = false;
如果写了@RequestParam,默认情况下 required = true;
(2)另外注意 在类的上边有 @RequestMapping("/home"),表示,只有在请求是资源"/home"下面才会处理;
例如 :
请求:
一个hello工程
localhost:8080/hello/default.html
localhost:8080/hello/test/home/default.html
将不被处理
localhost:8080/hello/home/default.html
将会被处理