1.配置SpringMVC-Servlet.xml
<!-- 注解扫描包,在这个包下的类都会启用注解 --> <context:component-scan base-package="com.tgb.web.controller.annotation" /> <!-- 开启注解 2种皆可--> <mvc:annotation-driven /> <!--<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean> -->
2.Controller类UserController.java 应当在自定义包com.tgb.web.controller.annotation下
关键字: @Controller ,@RequestMapping(value="",method=),不指定method的话,可以支持post和get
@Controller public class UserController { @RequestMapping(value = "/user/addUser",method=RequestMethod.POST) public ModelAndView addUser() { String result = "---addUser test---"; return new ModelAndView("/annotationTest","result",result); } @RequestMapping(value = "/user/delUser") public ModelAndView delUser() { String result = "---delUser test---"; return new ModelAndView("/annotationTest", "result", result); } @RequestMapping(value = "/user/toUser") public ModelAndView toUser() { return new ModelAndView("/annotationTest"); } }
优化:可以把根目录写到类名上面,方法的@RequestMapping中的value=可以不写。另外,除了返回ModelAndView类型外,还可以返回String类型,即是返回要反问的请求:
@Controller @@RequestMapping("/user") public class UserController { @RequestMapping("/addUser") public String addUser(HttpServletRequest request, HttpServletResponse response) { String result = "---addUser test---"; request.setAtrribute("result",result); //传递参数 return String "/annotationTest"; } @RequestMapping("/delUser") public ModelAndView delUser(HttpServletRequest request, HttpServletResponse response) { String result = "---delUser test---"; request.setAtrribute("result",result); return String "/annotationTest"; } @RequestMapping("/toUser") public String toUser(){ return String "/annotationTest"; } }
3.请求页面 annotationTest.jsp
<body> <form action="<%=request.getContextPath()%>/user/toUser" method="post"> <div> ${result} </div> <input type="submit" value="POST请求"> </form> </body>
原文地址:http://my.oschina.net/jainpeng1003/blog/290463