Javaはブロックを使用する方式(コード詳細手順)

1774 ワード

ブログ主が自分で書いたデモのWeChatを使って興味がある人は見てもいいです。
https://blog.csdn.net/weixin_39592397/articale/detail/85242287
1.まずはスプリングmvc_servlet.xmlに傍受を配置する
//***はすべての要求を遮断します。  注意:ブロックはあなたのaction要求をブロックするだけです。jsp要求をブロックしたいならフィルターを使います。
2.クラスで下記のコードを作成します。これは登録事例です。
package com.demand.util;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class LoginInterceptor implements HandlerInterceptor{

       //      Handler           

       //    :     ,    。

public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}

       //      Handler    ,  ModelAndView    

       //     modelAndView  ,       (     )       ,            

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}

  //    handler         

 //    :      ,      

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

//return true;

        //         

String uri = request.getRequestURL().toString();

        //         login         return true    return false   

    if(uri.contains("login")||uri.contains("inputInfo")) {
  return true;
}
// a)      ,        
HttpSession session = request.getSession();
Object username = session.getAttribute("user");
if (username != null) {
// b)        。  
return true;
}
response.sendRedirect(request.getContextPath() + "/login/index.action");
return false;
}
}