1. 程式人生 > >java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHand

java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHand

楔子

使用ssm,HandlerInterceptorAdapter 時,獲取執行的方法,出現如下錯誤

java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
    at cn.zhuzi.kindle.interceptor.PrivilegeInterceptorAdapter.preHandle(PrivilegeInterceptorAdapter.java
:38) at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:133) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:962) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901
) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

出錯事例

public class PrivilegeInterceptorAdapter extends HandlerInterceptorAdapter {
    @Resource
    JdbcTemplate jdbcTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object preHandle) throws
Exception { System.out.println(request.getRequestURI()); /* if (preHandle instanceof HandlerMethod) { */ //此處出現上述錯誤。使用了 HandlerMethod method = (HandlerMethod) preHandle; Prev pre = method.getMethod().getAnnotation(Prev.class); if (pre == null) { return true; } else { String oprator = pre.oprator(); String decription = pre.decription(); System.out.println("操作許可權-->" + decription); // TODO模擬 從session獲取許可權 @SuppressWarnings("unchecked") List<String> privilegeList = (List<String>) request.getSession().getAttribute("privilege"); if (privilegeList.contains(oprator)) { return true; } else { if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {// 是ajax請求 response.setCharacterEncoding("text/html;charset=UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); StringBuffer jsonTip = new StringBuffer("{\"result\":"); jsonTip.append(false).append(",\"tip\":\"您無權操作\"}"); writer.print(jsonTip.toString()); return false; } else {// 非ajax請求 String content = request.getSession().getServletContext().getContextPath(); // response.sendRedirect(content + // "/refuse.html");//轉發到頁面 response.setContentType("text/html;charset=utf-8"); response.getWriter().write("您無權操作"); return false; } } } }
-- 使用   System.out.println(request.getRequestURI()); 列印請求地址時 
發現,只有在請求資源找不到的情況下才會出現上述轉換錯誤。

解決
1 加上  if (preHandle instanceof HandlerMethod) { 做判斷
2 不處理,因為請求的資源不存在