【bf88必发唯一官网】过滤未登陆客户跳转到登陆页面,Java丨轻巧的登入过滤器达成情势

by admin on 2019年9月21日

一、编写SessionFilter.scala代码

过滤过滤,实际正是把供给和没有须求的事物分开!

  完毕思路是编写制定过滤器,假设客户登入之后session中会存一个user。倘诺未登陆就为null,就足以通过过滤器将客户重定向到登入页面,让客商张开登录,当然过滤器得决断客户访谈的比如是登入需要需求放行,假如不是就需求张开拦截并拓宽认证。登入成功再session存存入user,那样过滤器每回都会经过。

package filtersimport javax.inject.{Inject, Singleton}import akka.stream.Materializerimport controllers.routesimport play.api.mvc.{Filter, RequestHeader, Result, Results}import scala.concurrent.Future@Singletonclass SessionFilter @Inject()(implicit val mat: Materializer) extends Filter {  def apply(nextFilter: RequestHeader => Future[Result])           (requestHeader: RequestHeader): Future[Result] = {    if (!requestHeader.session.get.isDefined && !requestHeader.path.contains("/signin") && !requestHeader.path.contains("/assets/")) {      Future.successful(Results.Redirect(routes.SignController.showSignin    } else {      nextFilter(requestHeader)    }  }}

前日来合计说道大家先后中的‘登入过滤器’ ,首先大家看看一下边包车型大巴主题素材:

1.率先编写验证登录的过滤器

说明:

1、报到过滤器”是干吗用的?

package danger.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import danger.bean.sys.User;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

    /**
     * Default constructor.
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI();
        System.out.println("reqURL----------" + path);
        // 如果包含login.jsp证明是登陆就放行
        if (path.contains("login") || path.contains("/js/") || path.contains("/image/") || path.contains("/css/")
                || path.contains("message.jsp")|| path.contains("404.jsp")|| path.contains("")) {
            chain.doFilter(request, response); // 放行
            return;
        }
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        User user =  (User) session.getAttribute("user");
        // 如果session中存在user证明用户登录,可以放行。否则认为未登陆重定向到login.jsp
        if (user == null) {
            res.sendRedirect(req.getContextPath() + "/login/login.jsp");
        } else {
            System.out.println("user----------"+user);
            chain.doFilter(request, response);
        }

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

!requestHeader.session.get.isDefined 是用来判别session中是或不是留存user

1)登陆过滤器固然为了防御在客户从没登陆的地方下来拜会大家的网址。

 

!requestHeader.path.contains(“/signin”)
是用来祛除登录页面,那个页面不记名也理应是可知的,幸免现身死循环跳转

2)比如:main.html
这么些网页是内需通过login.html那些网页登入后才足以访谈的,未来有贰个顾客并未有登入,间接待上访谈main.html成功了。那么,那样的网址是或不是认为不安全呢?顾客不用登入随随意便就访谈了。so,we
have to need a
filter.我们需求用过滤器来过滤一些急需登陆后能力够访谈的页面.

 

!requestHeader.path.contains(“/assets/”)
是用来撤销静态能源文件的,如图片、css、JavaScript等

 

   if (path.contains(“login”) ||
path.contains(“/js/”) || path.contains(“/image/”) ||
path.contains(“/css/”) ||
path.contains(“message.jsp”)|| path.contains(“404.jsp”)||
path.contains(“”)) {
chain.doFilter(request, response); // 放行 return;
}      相当于是对登录央浼以及一些静态能源放行。(能够将一部分静态财富放到统一的文本夹上边)

二、在app目录下的Filters.scala中利用SessionFilter

2、大家要怎么过滤呢?

 

Filters.scala这几个文件是activator自动生成的模版,要选取SessionFilter只要在中间增添sessionFilter:
SessionFilter和Seq(sessionFilter)就足以了

【bf88必发唯一官网】过滤未登陆客户跳转到登陆页面,Java丨轻巧的登入过滤器达成情势。1)at first ! 我们断定要过滤掉需求登陆的页面

 

import javax.inject._import filters.{ExampleFilter, SessionFilter}import play.api._import play.api.http.HttpFiltersimport play.api.mvc._/** * This class configures filters that run on every request. This * class is queried by Play to get a list of filters. * * Play will automatically use filters from any class called * `Filters` that is placed the root package. You can load filters * from a different class by adding a `play.http.filters` setting to * the `application.conf` configuration file. * * @param env Basic environment settings for the current application. * @param exampleFilter A demonstration filter that adds a header to * each response. */@Singletonclass Filters @Inject() (  env: Environment,  exampleFilter: ExampleFilter, sessionFilter: SessionFilter) extends HttpFilters {  override val filters = {    // Use the example filter if we're running development mode. If    // we're running in production or test mode then don't use any    // filters at all.    if (env.mode == Mode.Dev) Seq(exampleFilter) else Seq.empty    Seq(sessionFilter)  }}

2)大家获得了亟待报到的页面后,大家怎么判别客商有未有记名呢?so,we need
a session .

 2.web.xml进行布署

原创文章,转发请证明出处。

3)已session为基于,来剖断客户是还是不是登陆过了。登陆过了大家就让他持续访谈,未有登陆的我们就让他回到到登入界面。

    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>danger.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

上面大家来会见代码是什么贯彻的:

 

package com.haojieli.filter;

 3.举行测量检验:

import java.io.IOException;

【bf88必发唯一官网】过滤未登陆客户跳转到登陆页面,Java丨轻巧的登入过滤器达成情势。类外号叫danger。再浏览器访问:

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

 

public class LoginFilter implements Filter{

调整台打字与印刷:

    public void destroy() {
        // TODO Auto-generated method stub
    }

reqURL----------/danger/login/login.jsp
reqURL----------/danger/js/jquery-1.11.js
reqURL----------/danger/controls/login/js/gVerify.js
reqURL----------/danger/controls/login/css/login2.css
reqURL----------/danger/controls/login/js/login.js
reqURL----------/danger/image/logo.png
reqURL----------/danger/controls/login.jpg

    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest req = (HttpServletRequest)arg0;
        HttpServletResponse resp =(HttpServletResponse) arg1;
        HttpSession session = req.getSession();
           // 得到顾客诉求的ULacrosseI
        String path = req.getRequestURI();
        // 从session获得已经报到验证的凭据
小编这里的demo用的是password来作为登陆凭证
        String password = (String) session.getAttribute(“password”);
        // login.jsp页面无需过滤(根据本人项目的供给来)

 

   //也能够path.contains(“login.jsp”)  反正怎么正确怎么来就非常少说了
        if(path.indexOf(“/login.jsp”) > -1)
{//注意:登入页面千万无法过滤 
不然过滤器就。。。。。自行调度不要偷懒!那样回想深刻
            arg2.doFilter(req, resp);
            return;
        } else {//若是否login.jsp实行过滤
              if (password == null || “”.equals(password)) {
                  // 跳转到登入页面
                  resp.sendRedirect(“login.jsp”);
            } else {
                // 已经登入,继续这次央浼
                arg2.doFilter(req, resp);
            }
        }
    }
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
}

 

在这里就不用解释代码了,代码中有详实的笺注,可是首要的一点
我们过滤器是写好了 ,还索要配备啊,不然怎么运转吧?followe me。

 页面被送到登录分界面。

将过滤器配置到web.xml里面 

bf88必发唯一官网 1

 <filter>
      <filter-name>Login</filter-name>
    
 <filter-class>com.haojieli.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>adminLogin</filter-name>

 

<!–这里的/admin/* 表示是钦赐路径下的文书须要过滤  
也得以写为 <url-pattern>/*</url-pattern>
表示全体文件都亟需过滤–>
      <url-pattern>/admin/*</url-pattern>
  </filter-mapping>

 

注意:登入页面不可能过滤。。。自行调治不要偷懒!那样纪念深切……

 

 

4.对登入的拍卖:(剖断顾客名与密码,并在session中增添user属性)

bf88必发唯一官网,登入表单(客商名与密码的name与Action的习性名字同样)

                    <form action="<%=path %>/login.action" name="loginform" accept-charset="utf-8" id="login_form" class="loginForm"
                          method="post"><input type="hidden" name="did" value="0"/>
                        <input type="hidden" name="to" value="log"/>
                        <div class="uinArea" id="uinArea">
                            <label class="input-tips" for="u">帐 &nbsp;号:</label>
                            <div class="inputOuter" id="uArea">
                                <input type="text" id="u" name="username" class="inputstyle"/>
                            </div>
                        </div>
                        <!--密码-->
                        <div class="pwdArea" id="pwdArea">
                            <label class="input-tips" for="p">密 &nbsp;码:</label>
                            <div class="inputOuter" id="pArea">
                                <input type="password" id="p"  name="password" class="inputstyle"/>
                            </div>
                        </div>
                        <!--验证码-->
                        <div class="yzmArea" id="verifyArea">
                            <label class="input-tips" for="code_input">验证码:</label>
                            <div class="inputOuter" id="yArea">
                                <input type="text" id="code_input" name="y" class="inputstyle"/>
                                <div id="v_container"></div>
                            </div>
                        </div>
                        <!--登录按钮-->

                        <div id="loginbuttondiv" class="inputOuter">
                            <input type="submit" value="登 录" class="button_blue" id="my_button"/>
                        </div>
                    </form>

 

管理登入的action

静态模拟八个顾客,并未有顾客分配差异的权力。(2代表是顶级顾客,能够扩充系统一管理理)

package danger.action.queryView;

/**
 * 登陆Action
 */
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import danger.bean.sys.User;
import danger.utils.ValidateCheck;

@Controller
@Scope("prototype")
public class LoginAction extends ActionSupport {
    private Map<String, Object> result;
    private String username;
    private String password;
    private User user;

    @Override
    public String execute() throws Exception {
        result = new HashMap();
        // 获取session
        HttpSession session = ServletActionContext.getRequest().getSession();
        // 用户名与密码不为空进行登陆验证
        if (ValidateCheck.isNotNull(username) && ValidateCheck.isNotNull(password)) {
            // 模拟登陆成功后session中添加user
            if ("root".equals(username) && "123456".equals(password)) {
                user = new User();
                user.setUsername(username);
                user.setRole(2);
                session.setAttribute("user", user);
                return SUCCESS;
            }
            if ("信息录入人员".equals(username) && "123456".equals(password)) {
                user = new User();
                user.setRole(1);
                user.setUsername(username);
                session.setAttribute("user", user);
                return SUCCESS;
            }
        }
        // 来到这里证明登陆未成功
        result.put("msg", "账户或者密码错误");
        return ERROR;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Map getResult() {
        return result;
    }

    public void setResult(Map result) {
        this.result = result;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

 

struts.xml   配置(登入成功后跻身主页,退步后到message.jsp突显错误新闻)

        <!-- 登陆 -->
        <action name="login" class="loginAction">
            <result name="success" type="redirect">/index.jsp</result>
            <result name="error">/message.jsp</result>
        </action>

 

博文到此甘休,感激您的见到,希望对各位读者有所帮衬,假诺有啥意见以及建议请在议论纷繁留言……

5.脱离系统的拍卖(删除session中的user,并将顾客重定向到三个页面)

管理退出的Action(清除session)

package danger.action.queryView;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class LogoutAction extends ActionSupport {

    @Override
    public String execute() throws Exception {
        // 获取session
        HttpSession session = ServletActionContext.getRequest().getSession();
        // 清空session中的用户
        session.removeAttribute("user");
        return super.execute();
    }
}

 

struts.xml配置Action

        <!-- 退出 -->
        <action name="logout" class="logoutAction">
            <!-- 成功后送到登陆页面 -->
            <result name="success" type="redirect">/login/login.jsp</result>
        </action>

 

 

退出系统开关

<a href=javascript:void(0)
                        style="text-decoration: none; color: white;" onclick="logout()">退出系统</a>

 

处理退出系统的JS函数

 

    <script type="text/javascript">
        function logout() {
            if (confirm("确定退出系统?")) {
                window.location.href = "${baseurl}/logout.action"
            }
        }
    </script>

 

======祝各位读者生活欢畅======

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图