SpringMVC Controller配置方式

在SpringMVC中,對於Controller的配置方式有很多種,如下做簡單總結

第一種 URL對應Bean

如果要使用此類配置方式,需要在XML中做如下樣式配置

<!-- 表示將請求的URL和Bean名字映射-->  
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>  
<bean name="/hello.do" class="com.wc..HelloController"></bean>

以上配置,訪問/hello.do就會尋找ID爲/hello.do的Bean,此類方式僅適用小型的應用系統


第二種 爲URL分配Bean

使用一個統一配置集合,對各個URL對應的Controller做關係映射

這是最常用的映射配置方式

<!-- 最常用的映射配置方式 -->  
<!-- <prop key="/hello*.do">helloController</prop>-->  
<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 name="helloController" class="com.wc.controller.HelloController"></bean>

此類配置還可以使用通配符,訪問/hello.do時,Spring會把請求分配給helloController進行處理


第三種 URL匹配Bean

如果定義的Controller名稱規範,也可以使用如下配置

<!-- 將hello*.do交給helloController處理-->  
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean>  
<bean id="helloController" class="test.HelloController"></bean>


第四種 註解

首先在配置文件中開啓註解

<!-- 使用spring組件掃描該包下的註解 -->
<context:component-scan base-package="com.wc.controller" />
package com.wc.controller;

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.servlet.ModelAndView;

@Controller

public class HelloController {
	@RequestMapping("/hello")//映射
	public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp){

		ModelAndView mv = new ModelAndView();
		//封裝要顯示到視圖中的數據
		mv.addObject("msg","hello springmvc annotation");
		//視圖名
		mv.setViewName("hello"); //WEB-INF/jsp/hello.jsp
		return mv;
	}	
}


在編寫類上使用註解@org.springframework.stereotype.Controller標記這是個Controller對象

使用@RequestMapping("/hello.do")指定方法對應處理的路徑,這裏只是簡單示例,會有更復雜配置

代碼類如下:

<!-- 使用spring組件掃描該包下的註解 -->
<context:component-scan base-package="com.wc.controller" />  
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
package test;  
import java.util.Date;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.web.bind.annotation.RequestMapping;  
// http://localhost:8080/spring/hello.do?user=java  
@org.springframework.stereotype.Controller  
public class HelloController{  
    @SuppressWarnings("deprecation")  
    @RequestMapping("/hello.do")  
    public String hello(HttpServletRequest request,HttpServletResponse response){  
        request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString());  
        return "hello";  
    }  
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章