javaweb-実験 9 補足演習-レビュー

javaweb-experiment 9 つの補足演習

word资料自提,见文章末尾

1. 機密性の高い単語のフィルタリングを実装します。

入力されたコメント内容にデリケートな単語がない場合はタグ「善人」と元のコメント内容が返され、コメント内容にデリケートな言葉が含まれている場合はタグ「悪い人」とコメント内容が「」に置き換えられます。 **」が返されます。
ここに画像の説明を挿入します

【実験手順】

(1) 「web9_extra」という名前の新しいプロジェクト(Webアプリケーション)を作成します。プロジェクト内に新しい「JSP」ファイルを作成し、「comment」という名前を付けます。comment.jsp はコメント インターフェイスを提供します。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>评论</title>
    </head>
    <body>
        <h1>输入评论内容</h1>
        <form action="<%= request.getContextPath()%>/comment" method="post">
            <textarea name="comment" cols="30" rows="10"></textarea>
            <input type="submit" value="提交">
        </form>
        <p><%= request.getAttribute("tag") == null ? "" : request.getAttribute("tag")%>
            <span style="color:red"><%=request.getAttribute("comment") == null ? "" : request.getAttribute("comment")%></span>
        </p>
    </body>
</html>

(2) 新しい「it.servlet」パッケージを作成し、このパッケージ内に新しい Java クラスを作成し、「CommentServlet」という名前を付けます。CommentServlet.java の機能: コメント内に機密用語が含まれているかどうかに応じて、異なるデータをコメント インターフェイスに転送します。

package it.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    
    
    private List<String> sensitiveWords = new ArrayList<>();
    @Override
    public void init() throws ServletException {
    
    
        sensitiveWords.add("山寨");
        sensitiveWords.add("盗版");
        sensitiveWords.add("水货");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //【代码一】获取评论内容(注意:post请求体中的数据的中文处理)
          // 先处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String comment = request.getParameter("comment");

        String originalComment = comment; //保存原评论

        for (String sensitiveWord : sensitiveWords) {
    
    
            //对所有敏感词汇进行过滤
            if (comment.contains(sensitiveWord)){
    
    
                //替换敏感词汇
                comment = comment.replace(sensitiveWord, "**");
            }
        }

       if (comment.equals(originalComment)/*【代码二】*/){
    
    
            //没有敏感词,设置tag为good guy
            request.setAttribute("tag","good guy:");
        }else {
    
    
            //有敏感词,设置tag为bad guy
            request.setAttribute("tag","bad guy:");
        }
       //【代码三】将comment保存到request中
       request.setAttribute("comment", comment);
        //【代码四】跳转到comment.jsp页面(请求转发?还是重定向?)
      request.getRequestDispatcher("/comment.jsp").forward(request,response);
    }
}

2. Cookie とセッションを使用して、ユーザーが welcome.jsp ページにアクセスしたときに 7 日間パスワード不要のログイン機能を実装します。具体的な要件は次のとおりです。

(1)login.jsp:ログインページ。

ここに画像の説明を挿入します
(2) LoginServlet: ログインが成功したかどうかを判断します。ユーザーが正常にログインすると、ユーザー名がセッションに保存されます。ユーザーがログインに成功し、login.jsp で「Remember Me」を選択すると、ユーザー名とパスワードが Cookie に 7 日間保存されます。
(3) welcome.jsp: 「***、ようこそ!」と表示されるウェルカム ページ。
まずセッションからユーザー名を読み取ります。セッションにユーザー名が存在しない場合は、ユーザー名とパスワードが Cookie から読み取られます。正しいユーザー名とパスワードが Cookie から読み取られた場合は、ユーザーが login.jsp で「Remember Me」を選択したことを意味し、ユーザーが再度ログインすることなく、Cookie から読み取られたユーザー名がページに表示されます。このようにして、welcome.jsp ページへの 7 日間パスワードなしのログインが実現します。
ここに画像の説明を挿入します
(4) LogoutServlet: セッション内のデータと Cookie をクリアして、「ログアウト」機能を実装します。

[実験手順]:

(1) プロジェクト内に新しい JSP を作成し、「login」という名前を付けます。

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div style="color:red"><%= request.getAttribute("error") == null ? "" : request.getAttribute("error")%></div>
        <form action="<%= request.getContextPath()%>/login" method="post">
            <table>
                <tr>
                    <td>用户名</td><td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>密码</td><td><input type="password" name="userpass"></td>

                </tr>
                <tr>
                    <td colspan="2"><input type="checkbox" name="remember" id="remember" value="yes"><label for="remember">记住我</label> </td>
                </tr>
                <tr>
                    <td><input type="submit" value="登录"></td>
                    <td><input type="reset" value="重置"></td>
                </tr>
            </table>           
        </form>
    </body>
</html>

(2) 「it.servlet」パッケージ内に新しい Java クラスを作成し、「LoginServlet」という名前を付けます。
LoginServlet.javaの機能:ログイン認証と7日間ログイン不要判定。

package it.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //接收前端数据
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        String remember = request.getParameter("remember");

        if ("admin".equals(username) && "123456".equals(userpass)) {
    
    
            //登录成功

            //勾选了“记住我”,remember的值为“yes”;如果没有勾选,remember的值为null
            if ("yes".equals(remember)/*【代码一】*/) {
    
    
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("userpass", userpass);
                //设置cookie携带路径为整个项目都携带
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                //设置cookie有效期(7天),cookie的过期时间是基于秒设置的
                cookie1.setMaxAge(60 * 60 * 24 * 7);
                cookie2.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie1);
                response.addCookie(cookie2);

            } else {
    
    
                Cookie cookie1 = new Cookie("username", "");
                Cookie cookie2 = new Cookie("userpass", "");
                cookie1.setMaxAge(0);
                cookie2.setMaxAge(0);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 用户名存入session
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            //重定向到welcome.jsp
            response.sendRedirect(request.getContextPath() + "/welcome.jsp");
            return;
        }
        //【代码二】登录失败,将错误信息“用户名或密码错误”转发给login.jsp
        request.setAttribute("error", "用户名或密码错误");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}

(3) 新しい JSP を作成し、「welcome」という名前を付けます。welcome.jsp はウェルカム ページです。

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
<%
    // 先判断session中是否有用户名
    String username = (String) session.getAttribute("username");
    String userpass = null;
    if (username == null) {
    
    
       /* session中没有用户名,即:用户没有经过LoginServlet的登录成功的验证(用户没有登录过),则判断Cookie中是否有用户名,如果有,则说明用户之前登录时选择了“记住我”*/

        //【代码三】从cookie中读取用户名和密码
       Cookie[] cookies = request.getCookies();

        if (username != null && userpass != null) {
    
      //用户选择过“记住我”(免密登录)
            if ("admin".equals(username) && "123456".equals(userpass)) {
    
    
                //【代码四】cookie中的用户名和密码正确,将用户名存储到session
               /* 存储到session的目的是,之后只要还是在一次会话中访问welcome.jsp,则直接从session中读取用户名,而不再访问cookie*/
				session.setAttribute("username", username);
                
            } else {
    
    //session中无用户名;cookie中有用户名和密码,但cookie中的用户名或密码不正确,跳转到登录页面
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }
        } else {
    
    //session中无用户名;cookie中无用户名或密码,即:用户没有选择免密登录,则跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
    }    
%>
<%--session中有用户名;或者:session中无用户名,但cookie中存储了正确的用户名和密码,则显示“***,欢迎您!”--%>
<%=username%>,欢迎您!<a href="<%=request.getContextPath()%>/logout">退出登录</a>
</body>
</html>

(4) Java パッケージ「it.servlet」内に新しい Java クラスを作成し、「LogoutServlet」という名前を付けます。LogoutServlet.java の機能: ログアウト。

package it.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    
    

    @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        /* 【代码五】清除当前登录用户名(session中的username)以及cookie中的username和userpass */
		HttpSession session = req.getSession();
        session.removeAttribute("username");
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
    
    
            for (Cookie cookie : cookies) {
    
    
                if("username".equals(cookie.getName())
||"userpass".equals(cookie.getName())) {
    
    
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }
           }
        }
resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

}

3. 具体的な実装

最初の質問の実現:

package it.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther zg
 * @Date 2023/12/20
 * @Version 1.0
 */
@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    
    
    private List<String> sensitiveWords = new ArrayList<>();
    @Override
    public void init() throws ServletException {
    
    
        sensitiveWords.add("山寨");
        sensitiveWords.add("盗版");
        sensitiveWords.add("水货");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //【代码一】获取评论内容(注意:post请求体中的数据的中文处理)
        // 先处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String comment = request.getParameter("comment");

        String originalComment = comment; //保存原评论

        for (String sensitiveWord : sensitiveWords) {
    
    
            //对所有敏感词汇进行过滤
            if (comment.contains(sensitiveWord)){
    
    
                //替换敏感词汇
                comment = comment.replace(sensitiveWord, "**");
            }
        }

        if (comment.equals(originalComment)/*【代码二】*/){
    
    
            //没有敏感词,设置tag为good guy
            request.setAttribute("tag","good guy:");
        }else{
    
    
            //有敏感词,设置tag为bad guy
            request.setAttribute("tag","bad guy:");
        }
        //【代码三】将comment保存到request中
        request.setAttribute("comment", comment);

        //【代码四】跳转到comment.jsp页面(请求转发?还是重定向?)
        request.getRequestDispatcher("/comment.jsp").forward(request,response);

    }
}

2 番目の疑問は次のように実現されます。

package it.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Auther zg
 * @Date 2023/12/20
 * @Version 1.0
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //接收前端数据
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        String remember = request.getParameter("remember");

        if ("admin".equals(username) && "123456".equals(userpass)) {
    
    
            //登录成功

            //勾选了“记住我”,remember的值为“yes”;如果没有勾选,remember的值为null
            if ("yes".equals(remember)/*【代码一】*/) {
    
    
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("userpass", userpass);
                //设置cookie携带路径为整个项目都携带
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                //设置cookie有效期(7天),cookie的过期时间是基于秒设置的
                cookie1.setMaxAge(60 * 60 * 24 * 7);
                cookie2.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie1);
                response.addCookie(cookie2);

            } else {
    
    
                Cookie cookie1 = new Cookie("username", "");
                Cookie cookie2 = new Cookie("userpass", "");
                cookie1.setMaxAge(0);
                cookie2.setMaxAge(0);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 用户名存入session
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            //重定向到welcome.jsp
            response.sendRedirect(request.getContextPath() + "/welcome.jsp");
            return;
        }
        //【代码二】登录失败,将错误信息“用户名或密码错误”转发给login.jsp
        request.setAttribute("error", "用户名或密码错误");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}

<%--
  Created by IntelliJ IDEA.
  User: zg
  Date: 2023/12/20
  Time: 22:19
  To change this template use File | Settings | File Templates.
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JSP Page</title>
</head>
<body>
<%
  // 先判断session中是否有用户名
  String username = (String) session.getAttribute("username");
  String userpass = null;
  if (username == null) {
    
    
    /* session中没有用户名,即:用户没有经过LoginServlet的登录成功的验证(用户没有登录过),则判断Cookie中是否有用户名,如果有,则说明用户之前登录时选择了“记住我”*/

    //【代码三】从cookie中读取用户名和密码
    Cookie[] cookies = request.getCookies();

    if (username != null && userpass != null) {
    
      //用户选择过“记住我”(免密登录)
      if ("admin".equals(username) && "123456".equals(userpass)) {
    
    
        //【代码四】cookie中的用户名和密码正确,将用户名存储到session
        /* 存储到session的目的是,之后只要还是在一次会话中访问welcome.jsp,则直接从session中读取用户名,而不再访问cookie*/
        session.setAttribute("username", username);
      } else {
    
    //session中无用户名;cookie中有用户名和密码,但cookie中的用户名或密码不正确,跳转到登录页面
        response.sendRedirect(request.getContextPath() + "/login.jsp");
        return;
      }
    } else {
    
    //session中无用户名;cookie中无用户名或密码,即:用户没有选择免密登录,则跳转到登录页面
      response.sendRedirect(request.getContextPath() + "/login.jsp");
      return;
    }
  }
%>
<%--session中有用户名;或者:session中无用户名,但cookie中存储了正确的用户名和密码,则显示“***,欢迎您!”--%>
<%=username%>,欢迎您!<a href="<%=request.getContextPath()%>/logout">退出登录</a>
</body>
</html>


package it.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Auther zg
 * @Date 2023/12/20
 * @Version 1.0
 */
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        /* 【代码五】清除当前登录用户名(session中的username)以及cookie中的username和userpass */
        HttpSession session = req.getSession();
        session.removeAttribute("username");

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
    
    
            for (Cookie cookie : cookies) {
    
    
                if ("username".equals(cookie.getName()) || "userpass".equals(cookie.getName())) {
    
    
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }
            }
        }
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

}

4. 情報のセルフピックアップ (有効期限が切れた場合は、メッセージを残してください)

リンク: https://pan.baidu.com/s/11G8k74f2-fsrG6eKFKfjPw?pwd=bmud
抽出コード: bmud

おすすめ

転載: blog.csdn.net/qq_52495761/article/details/135119332