controller配置汇总

来源:互联网 发布:剑三男捏脸数据 编辑:程序博客网 时间:2024/06/06 01:31

1.通过URL对应Bean

<pre name="code" class="html"><!-- 配置HandlerMapping 根据beanname找对对应的controller -->

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>       <!-- 配置handleradapter -->       <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<span style="white-space:pre"></span><!-- 配置controller -->       <bean name="/hello.do" class="cn.com.jit.controller.HelloController"/>
以上配置访问/hello.do就会寻找ID为/hello.do的Bean,此类方式仅使用小型应用系统


2.为URL分配Bean

使用一个统一配置集合,对各个URL对应的Controller做关系映射

<!-- 最常用的 -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">       <property name="mappings">       <props>       <!-- key 对应URL请求名   value 对应处理器的ID-->       <prop key="/hello.do">hellocontroller</prop>       </props>       </property>       </bean>       <bean id="hellocontroller" class="cn.com.jit.controller.HelloController"></bean>
此类配置还可以使用通配符,访问/hello.do时,Spring会把请求分配给helloController进行处理。


3.URL匹配Bean

如果定义的Conroller名称规范,也可以使用如下配置

<!-- 将hello*.do交给helloController去处理 --> 
<!-- 配置HandlerMapping 根据beanname找对对应的controller -->       <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>       <!-- 配置controller  请求为hello*.do都将会被匹配 -->       <bean name="/helloController" class="cn.com.jit.controller.HelloController"/>


4注解

 <!-- 配置springMVC 注解驱动 -->       <mvc:annotation-driven/>       <!-- 扫描器 -->       <context:component-scan base-package="cn"></context:component-scan>
在controller中添加注解:

@Controller@RequestMapping("/user")public class UserController {/** * 时间编辑器 */ @InitBinder   public void initBinder(ServletRequestDataBinder binder) {       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");       //dateFormat.setLenient(false);       binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }@RequestMapping("/add1.do")public String add(HttpServletRequest request){String username = request.getParameter("username");String password = request.getParameter("password");System.out.println("username:" + username + "---" + "password:" + password);return "user/user_list";}@RequestMapping("/add2.do")public String add2(String username, String password ){System.out.println("username:" + username + "-----" + "password:" + password);return "user/user_list";}@RequestMapping("/add3.do")public String add3(UserInfo userInfo){System.out.println(userInfo);return "user/user_list";}@RequestMapping("/add4.do")public String add4(String userName, Date date){System.out.println("username:" + userName + "---" + "date:" + date);return "user/user_list";}}





0 0
原创粉丝点击