欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

servlet實現(xiàn)簡單的權(quán)限管理和敏感詞過濾功能

 更新時間:2021年05月27日 15:00:18   作者:Dreamchaser追夢  
JavaEE課要求用servlet和過濾器實現(xiàn)權(quán)限管理和敏感詞過濾功能,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

JavaEE課要求用servlet和過濾器實現(xiàn)權(quán)限管理和敏感詞過濾功能,故有此文。
雖然早已知道了原理和用法,但是實際操作起來還是遇到了各種奇葩的情況。

一、如何實現(xiàn)權(quán)限管理

1.思路

當(dāng)用戶訪問某個資源時,我們必須對其權(quán)限控制,所以得用到servlet中過濾器來對請求做一次預(yù)處理,判斷該用戶是否有權(quán)限訪問該資源,如果有則放行;如果沒有則返回拒絕訪問的通知。

那么我們?nèi)绾闻袛嘣撚脩羰欠裼袡?quán)限訪問呢?
這就要求我們在用戶登錄的時候保存其登錄狀態(tài)。

可我們知道http請求是無狀態(tài)的,即這次請求無法知道上一次請求的內(nèi)容,那如何保存這個登錄狀態(tài)呢?

這就需要要用到Session/Cookie機(jī)制(這里我就不多介紹了,感興趣的可以去百度,當(dāng)然我在手把手教你用Java實現(xiàn)一套簡單的鑒權(quán)服務(wù)(SpringBoot,SSM)(萬字長文)這篇博文中說的很詳細(xì)了,感興趣的同學(xué)可以去看看)。

既然如此,那么我們在登錄成功的時候就把用戶的信息存入到服務(wù)器的session中,等用戶下次訪問的時候,我們就知道是哪位用戶以及這位用戶有沒有權(quán)限訪問了。

至此我們便實現(xiàn)了簡單的權(quán)限控制。

但是這里有個地方需要注意,就是過濾器在攔截時需要排除一些路徑,比如登錄頁面,比如靜態(tài)資源。這個有很多方法,我采取的是我認(rèn)為比較簡單的方法,具體實現(xiàn)在下文。

2.代碼實現(xiàn)

①登錄頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>后臺管理-登陸</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="/static/lib/layui-v2.6.3/css/layui.css" rel="external nofollow"  media="all">
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        .main-body {top:50%;left:50%;position:absolute;-webkit-transform:translate(-50%,-50%);-moz-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);-o-transform:translate(-50%,-50%);transform:translate(-50%,-50%);overflow:hidden;}
        .login-main .login-bottom .center .item input {display:inline-block;width:227px;height:22px;padding:0;position:absolute;border:0;outline:0;font-size:14px;letter-spacing:0;}
        .login-main .login-bottom .center .item .icon-1 {background:url(../static/images/icon-login.png) no-repeat 1px 0;}
        .login-main .login-bottom .center .item .icon-2 {background:url(../static/images/icon-login.png) no-repeat -54px 0;}
        .login-main .login-bottom .center .item .icon-3 {background:url(../static/images/icon-login.png) no-repeat -106px 0;}
        .login-main .login-bottom .center .item .icon-4 {background:url(../static/images/icon-login.png) no-repeat 0 -43px;position:absolute;right:-10px;cursor:pointer;}
        .login-main .login-bottom .center .item .icon-5 {background:url(../static/images/icon-login.png) no-repeat -55px -43px;}
        .login-main .login-bottom .center .item .icon-6 {background:url(../static/images/icon-login.png) no-repeat 0 -93px;position:absolute;right:-10px;margin-top:8px;cursor:pointer;}
        .login-main .login-bottom .tip .icon-nocheck {display:inline-block;width:10px;height:10px;border-radius:2px;border:solid 1px #9abcda;position:relative;top:2px;margin:1px 8px 1px 1px;cursor:pointer;}
        .login-main .login-bottom .tip .icon-check {margin:0 7px 0 0;width:14px;height:14px;border:none;background:url(../static/images/icon-login.png) no-repeat -111px -48px;}
        .login-main .login-bottom .center .item .icon {display:inline-block;width:33px;height:22px;}
        .login-main .login-bottom .center .item {width:288px;height:35px;border-bottom:1px solid #dae1e6;margin-bottom:35px;}
        .login-main {width:428px;position:relative;float:left;}
        .login-main .login-top {height:117px;background-color:#148be4;border-radius:12px 12px 0 0;font-family:SourceHanSansCN-Regular;font-size:30px;font-weight:400;font-stretch:normal;letter-spacing:0;color:#fff;line-height:117px;text-align:center;overflow:hidden;-webkit-transform:rotate(0);-moz-transform:rotate(0);-ms-transform:rotate(0);-o-transform:rotate(0);transform:rotate(0);}
        .login-main .login-top .bg1 {display:inline-block;width:74px;height:74px;background:#fff;opacity:.1;border-radius:0 74px 0 0;position:absolute;left:0;top:43px;}
        .login-main .login-top .bg2 {display:inline-block;width:94px;height:94px;background:#fff;opacity:.1;border-radius:50%;position:absolute;right:-16px;top:-16px;}
        .login-main .login-bottom {width:428px;background:#fff;border-radius:0 0 12px 12px;padding-bottom:53px;}
        .login-main .login-bottom .center {width:288px;margin:0 auto;padding-top:40px;padding-bottom:15px;position:relative;}
        .login-main .login-bottom .tip {clear:both;height:16px;line-height:16px;width:288px;margin:0 auto;}
        body {background:url(../static/images/loginbg.png) 0% 0% / cover no-repeat;position:static;font-size:12px;}
        input::-webkit-input-placeholder {color:#a6aebf;}
        input::-moz-placeholder {/* Mozilla Firefox 19+ */            color:#a6aebf;}
        input:-moz-placeholder {/* Mozilla Firefox 4 to 18 */            color:#a6aebf;}
        input:-ms-input-placeholder {/* Internet Explorer 10-11 */            color:#a6aebf;}
        input:-webkit-autofill {/* 取消Chrome記住密碼的背景顏色 */            -webkit-box-shadow:0 0 0 1000px white inset !important;}
        html {height:100%;}
        .login-main .login-bottom .tip {clear:both;height:16px;line-height:16px;width:288px;margin:0 auto;}
        .login-main .login-bottom .tip .login-tip {font-family:MicrosoftYaHei;font-size:12px;font-weight:400;font-stretch:normal;letter-spacing:0;color:#9abcda;cursor:pointer;}
        .login-main .login-bottom .tip .forget-password {font-stretch:normal;letter-spacing:0;color:#1391ff;text-decoration:none;position:absolute;right:62px;}
        .login-main .login-bottom .login-btn {width:288px;height:40px;background-color:#1E9FFF;border-radius:16px;margin:24px auto 0;text-align:center;line-height:40px;color:#fff;font-size:14px;letter-spacing:0;cursor:pointer;border:none;}
        .login-main .login-bottom .center .item .validateImg {position:absolute;right:1px;cursor:pointer;height:36px;border:1px solid #e6e6e6;}
        .footer {left:0;bottom:0;color:#fff;width:100%;position:absolute;text-align:center;line-height:30px;padding-bottom:10px;text-shadow:#000 0.1em 0.1em 0.1em;font-size:14px;}
        .padding-5 {padding:5px !important;}
        .footer a,.footer span {color:#fff;}
        @media screen and (max-width:428px) {.login-main {width:360px !important;}
            .login-main .login-top {width:360px !important;}
            .login-main .login-bottom {width:360px !important;}
        }
    </style>
</head>
<body>
<div class="main-body">
    <div class="login-main">
        <div class="login-top">
            <span>LayuiMini后臺登錄</span>
            <span class="bg1"></span>
            <span class="bg2"></span>
        </div>
        <form class="layui-form login-bottom" action="/login" method="post">
            <div class="center">
                <div class="item">
                    <span class="icon icon-2"></span>
                    <input type="text" name="uname" lay-verify="required"  placeholder="請輸入登錄賬號" maxlength="24"/>
                </div>

                <div class="item">
                    <span class="icon icon-3"></span>
                    <input type="password" name="pwd" lay-verify="required"  placeholder="請輸入密碼" maxlength="20">
                    <span class="bind-password icon icon-4"></span>
                </div>

            </div>
            <div class="tip">
                <span class="icon-nocheck"></span>
                <span class="login-tip">保持登錄</span>
                <a href="javascript:" rel="external nofollow"  class="forget-password">忘記密碼?</a>
            </div>
            <div class="layui-form-item" style="text-align:center; width:100%;height:100%;margin:0px;">
                <button class="login-btn" type="submit" lay-submit="" lay-filter="login">立即登錄</button>
            </div>
        </form>
    </div>
</div>
<div class="footer">
    ©版權(quán)所有 2014-2018 叁貳柒工作室<span class="padding-5">|</span><a target="_blank"  rel="external nofollow" >粵ICP備16006642號-2</a>
</div>
<script src="/static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    //原本想用json的post發(fā)送,結(jié)果發(fā)現(xiàn)后端數(shù)據(jù)得自己解析,為了降低難度,直接用form表單的post提交,這樣后端直接拿數(shù)據(jù)即可(不然還得解析Json數(shù)據(jù))
    // layui.use(['form','jquery'], function () {
    //     var $ = layui.jquery,
    //         form = layui.form,
    //         layer = layui.layer;
    //
    //     // 登錄過期的時候,跳出ifram框架
    //     if (top.location != self.location) top.location = self.location;
    //
    //     $('.bind-password').on('click', function () {
    //         if ($(this).hasClass('icon-5')) {
    //             $(this).removeClass('icon-5');
    //             $("input[name='pwd']").attr('type', 'password');
    //         } else {
    //             $(this).addClass('icon-5');
    //             $("input[name='pwd']").attr('type', 'text');
    //         }
    //     });
    //
    //     $('.icon-nocheck').on('click', function () {
    //         if ($(this).hasClass('icon-check')) {
    //             $(this).removeClass('icon-check');
    //         } else {
    //             $(this).addClass('icon-check');
    //         }
    //     });
    //
    //     // 進(jìn)行登錄操作
    //     form.on('submit(login)', function (data) {
    //         data = data.field;
    //         if (data.uname == '') {
    //             layer.msg('用戶名不能為空');
    //             return false;
    //         }
    //         if (data.pwd == '') {
    //             layer.msg('密碼不能為空');
    //             return false;
    //         }
    //         $.ajax({
    //             url:'/login',
    //             method:'post',
    //             data:data,
    //             dataType:'JSON',
    //             success:function(res){
    //                 if (res.msg==='登錄成功'){
    //                     layer.msg('登錄成功', function () {
    //                         window.location = '../index.html';
    //                     });
    //                 }else {
    //                     layer.msg("登錄失敗");
    //                 }
    //             },
    //             error:function (data) {
    //             }
    //         }) ;
    //
    //
    //         return false;
    //     });
    // });
</script>
</body>
</html>

因為上面我并沒有給出圖片,css等靜態(tài)資源,所以直接復(fù)制是沒有我這里的效果的。

下面這樣也是可以的,

<!DOCTYPE html>
<htmllang="en">
<head>
    <meta charset="UTF-8">
    <title>用戶登錄</title>
</head>
<body>
<form action="/login" method="post">
    用戶名:<input type="text" name="uname">
    密碼:<input type="password" name="pwd">
    <input type="submit" value="login">
</form>
 
</body>
</html>

②登錄Servlet類

具體驗證的邏輯我這里就不放了。這里登錄成功會將用戶名存入session,并自動跳轉(zhuǎn)首頁。

package com.dreamchaser.loginTest.servlet;

import com.dreamchaser.loginTest.mapper.UserMapper;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    static UserMapper userMapper=UserMapper.getUserMapper();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uname=req.getParameter("uname");
        String pwd=req.getParameter("pwd");
        ServletOutputStream outputStream = resp.getOutputStream();
        String result;
        if (pwd.equals(userMapper.getPwdByName(uname))){
            req.getSession().setAttribute("user",uname);
            resp.sendRedirect("/index.html");
        }else {
            //響應(yīng)
            result="登錄失敗";
            outputStream.write(result.getBytes());
        }
    }
}

③UserFilter過濾器

因為該過濾器配置的路徑是/*,即全部路徑,但是我們不想攔截一些路徑,比如登錄頁面,靜態(tài)資源,所以我們在操作前進(jìn)行一次判斷,避免這些路徑的處理。

注:innit方法會將配置中排除的路徑讀取過來,當(dāng)然你也可以寫在程序里

package com.dreamchaser.loginTest.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class UserFilter implements Filter {

    private List excludedUrls;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        // 將req resp 轉(zhuǎn)為子接口的類型
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String path = request.getServletPath();

        if(!excludedUrls.contains(path)&&!(path.length()>8&&"/static/".equals(path.substring(0,8))))
        {
            if (request.getSession().getAttribute("user")==null){
               response.sendRedirect("/pages/login.html");
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludePattern = filterConfig.getInitParameter("excludedUrls");
        excludedUrls = Arrays.asList(excludePattern.split(","));
    }

    @Override
    public void destroy() {
    }
}

④web.xml配置項

init-param標(biāo)簽里存放的是排除在外的路徑,這個是自己定義的。

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.dreamchaser.loginTest.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>UserFilter</filter-name>
    <filter-class>com.dreamchaser.loginTest.filter.UserFilter</filter-class>
    <init-param>
      <param-name>excludedUrls</param-name>
      <param-value>/pages/login.html,/register.html,/login</param-value>
    </init-param>

  </filter>
  <filter-mapping>
    <filter-name>UserFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

二、敏感詞過濾

1.思路

利用過濾器提前對請求里要過濾的屬性進(jìn)行處理,但是因為沒有setParameter方法(這是故意的,設(shè)計者就是不想讓我們直接修改),所以我們?yōu)榱舜娣胚^濾后的信息,可以把過濾后的信息放在attribute中,然后servlet直接獲取即可。(當(dāng)然也可以重寫一個Request類,那個比較麻煩,感興趣的自行百度)

2.代碼實現(xiàn)

①敏感詞過濾頁

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/word" method="post" style="margin-top: 300px">
        請輸入你要說的垃圾話:<br><input name="word" style="width: 500px" type="text">
        <button type="submit"> 提交</button>
    </form>
</body>
</html>

②WordServlet類

從attribute中獲取過濾后的字符串后返回。

package com.dreamchaser.loginTest.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 需要敏感詞過濾的接口
 */
public class WordServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //因為servlet并沒有setParameter方法(這是故意的),所以過濾后word無法通過getparameter來獲取
        //所以一般有兩種方法一種把它放在attribute里,一種重寫Request類,不過這會很麻煩
        String word= String.valueOf(req.getAttribute("word"));
        ServletOutputStream outputStream = resp.getOutputStream();
        String result="詞匯已凈化,請放心食用:"+word;
        outputStream.write(result.getBytes());
    }
}

③WordFilter過濾器類

靜態(tài)常量sensitiveWords中存放的是需要過濾的字符串,harmoniousWord是過濾后的詞匯。
這里就是對需要過濾的借口提前進(jìn)行處理,把敏感詞換成注入“***”這樣的字符串,然后存放在attribute中。

package com.dreamchaser.loginTest.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 敏感詞過濾攔截器
 */
public class WordFilter implements Filter {
    static final String[] sensitiveWords={"敏感詞1","臟話","罵人"};
    static final String harmoniousWord="***";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        // 將req resp 轉(zhuǎn)為子接口的類型
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String word=req.getParameter("word");
        for (String s:sensitiveWords){
            word=word.replaceAll(s,harmoniousWord);
        }
        request.setAttribute("word",word);
        chain.doFilter(req, resp);
    }
}

web.xml配置項

<servlet>
    <servlet-name>WordServlet</servlet-name>
    <servlet-class>com.dreamchaser.loginTest.servlet.WordServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WordServlet</servlet-name>
    <url-pattern>/word</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>WordFilter</filter-name>
    <filter-class>com.dreamchaser.loginTest.filter.WordFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>WordFilter</filter-name>
    <url-pattern>/word</url-pattern>
  </filter-mapping>

三、效果展示

1.未登錄訪問其他資源

自動跳轉(zhuǎn)至登錄頁

在這里插入圖片描述

2.密碼錯誤,登錄失敗

在這里插入圖片描述

3.密碼正確,自動跳轉(zhuǎn)首頁

在這里插入圖片描述

4.刷新首頁,不會跳轉(zhuǎn)

在這里插入圖片描述

5.敏感詞過濾

在這里插入圖片描述

處理后返回結(jié)果

在這里插入圖片描述

注:代碼已開源至gitee,地址

到此這篇關(guān)于servlet實現(xiàn)簡單的權(quán)限管理和敏感詞過濾功能的文章就介紹到這了,更多相關(guān)servlet 權(quán)限管理和敏感詞過濾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談hibernate中多表映射關(guān)系配置

    淺談hibernate中多表映射關(guān)系配置

    下面小編就為大家?guī)硪黄獪\談hibernate中多表映射關(guān)系配置。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 解析Mybatis的insert方法返回數(shù)字-2147482646的解決

    解析Mybatis的insert方法返回數(shù)字-2147482646的解決

    這篇文章主要介紹了解析Mybatis的insert方法返回數(shù)字-2147482646的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • java程序代碼與文本對比實用工具簡介

    java程序代碼與文本對比實用工具簡介

    可以對兩段文本進(jìn)行對比,檢測/比較兩個文本有什么不同的差異,以便修改,常用于程序代碼,就是不需要人工查看,尤其是大文件,有幾百上千行的代碼,這時候就建議使用比較工具了,不用浪費過多時間去尋找
    2021-09-09
  • java處理csv文件上傳示例詳解

    java處理csv文件上傳示例詳解

    這篇文章主要為大家詳細(xì)介紹了java處理csv文件上傳示例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • Java Classloader機(jī)制用法代碼解析

    Java Classloader機(jī)制用法代碼解析

    這篇文章主要介紹了Java Classloader機(jī)制用法代碼解析,涉及JDK默認(rèn)ClassLoader,雙親委托模型,自定義ClassLoader等相關(guān)內(nèi)容,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • idea 開發(fā)神器之idea插件匯總

    idea 開發(fā)神器之idea插件匯總

    這篇文章主要介紹了idea 開發(fā)神器之idea插件匯總,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • SpringBoot整合PageHelper分頁無效的常見原因分析

    SpringBoot整合PageHelper分頁無效的常見原因分析

    這篇文章主要介紹了SpringBoot整合PageHelper分頁無效的常見原因分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 詳解JAVA中接口的定義和接口的實現(xiàn)

    詳解JAVA中接口的定義和接口的實現(xiàn)

    這篇文章主要介紹了JAVA中接口的定義和接口的實現(xiàn),文中講解非常細(xì)致,配合代碼更好的幫大家學(xué)習(xí)參考,感興趣的朋友可以了解下
    2020-06-06
  • Java配置win10環(huán)境變量過程圖解

    Java配置win10環(huán)境變量過程圖解

    這篇文章主要介紹了Java配置win10環(huán)境變量過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • 詳解MongoDB和Spring整合的實例代碼

    詳解MongoDB和Spring整合的實例代碼

    這篇文章主要介紹了詳解MongoDB和Spring整合的實例代碼,Spring提供了MongoTemplate這樣一個模板類的實現(xiàn)方法,簡化了具體操作。有興趣的可以了解一下
    2017-07-07

最新評論