SpringMVC常見註解mvc interceptors mvc view controller mvc resources mapping的用法
mvc:interceptors mvc:view-controller mvc:resources mapping都是SpringMVC配置檔案中常見的標籤,今天就根據具體程式碼來詳細介紹一下這兩個標籤的使用方法:
一、mvc:interceptors用法
1.配置攔截器
在springMVC.xml配置檔案增加:
<mvc:interceptors>
<!--介面攔截器 -->
<mvc:interceptor>
<mvc:mapping path="/anon/**/*.int" />
<bean class="com.by.frame.intfc.IntfaceSecurityInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
說明:
1)mvc:mapping 攔截器路徑配置
2)mvc:exclude-mapping 攔截器不需要攔截的路徑
3)bean class表示攔截器程式碼,詳細說明了這個攔截器的用途
程式碼如下圖所示:
public class IntfaceSecurityInterceptor extends HandlerInterceptorAdapter {
public static final Log logger = LogFactory.getLog(IntfaceSecurityInterceptor.class);
@Resource
private IASysClientKeyService aSysClientKeyService;
@Resource
private IASysPortLogService aSysPortLogService;
@Override
public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
………………
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
這個標籤使用的目的就是對於某些特殊的介面需要使用攔截器對其進行處理,例如:使用加密資料請求介面,需要在攔截器中對請求資料進行解密之後才可以進入controller。
二、mvc:view-controller用法
此註解主要用來實現首頁的重定向,在springMVC中配置如下:
<mvc:view-controller path="/" view-name="redirect:/frame/protal" />
<mvc:view-controller path="/index" view-name="redirect:/frame/protal" />
<mvc:view-controller path="/frame/index" view-name="redirect:/frame/protal" />
path表示訪問的path,view-name表示重定向後的path,上圖表示無論訪問的路徑是”/” “/index” 還是”/frame/index”,都要重定向到 “/frame/protal”。
關於重定向,有兩種方式:
1)、重定向
<mvc:view-controller path="/" view-name="redirect:/admin/index"/>
即如果當前路徑是/ 則重定向到/admin/index
2)、view name
<mvc:view-controller path="/" view-name=/admin/index"/>
如果當前路徑是/ 則交給相應的檢視解析器直接解析為檢視,然後可以根據viewResolver配置的prefix和suffix找到具體的檢視。
另外還有一種常用的重定向的方法,那就是在controller中重定向,
@Controller
@RequestMapping("/frame")
public class LogoutController extends BaseController {
@RequestMapping(value="/logout", method=RequestMethod.GET)
public String logout() {
SecurityUtils.getSubject().logout();
return "redirect:/frame/login";
}
}
當訪問 “/frame/logout”時,重定向到 “/frame/login”
三、mvc:resources mapping用法
採用spring自帶方法。首先找到你定義的那個servlet的xml檔案,如本例子中,servlet的名字叫mvc-dispatcher,因此需要找到mvc-dispatcher-servlet.xml檔案,並在該檔案中插入以下配置:
<mvc:resources mapping="/resources/**/" location="/resources/"/>
如此就不必另外新增一個mvc來處理靜態資源。而mvc知道靜態資源所處的位置為resources資料夾。
兩種方法都可以將spring mvc配置處理靜態資源。
在SpringMVC3.0之後推薦使用一:
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
說明:
location元素表示webapp目錄下的static包下的所有檔案;
mapping元素表示以/static開頭的所有請求路徑,如/static/a 或者/static/a/b;
該配置的作用是:DispatcherServlet不會攔截以/static開頭的所有請求路徑,並當作靜態資源
交由Servlet處理。