2-5作业检查

2-5作业检查

相关代码:

index.jsp

​<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%String flag = request.getParameter("flag"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var flag= <%=flag%>;
if(flag == "1"){
alert("你尚未登录;或者账号在异地登录;请重新登录");
}

</script>
</head>
<body>
<form action = "save.jsp" method="get" class = "login">
账号<input name = "username" type="text" placeholder = "请输入账号">
密码<input name = "password" type="text" placeholder = "请输入密码">
<input name="submit" type = "submit" value = "登录">
</form>
</body>
</html>

相关代码:

save.jsp

​<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%

String username = request.getParameter("username");
String password = request.getParameter("password");
//把账号存到LoginUser属性中
session.setAttribute("LoginUser",username);
response.sendRedirect("show.jsp");

%>
</body>
</html>

相关代码:

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<img alt="无法显示" src="images/111.png">
</body>
</html>

相关代码:

web.xml配置过滤器

​ <filter>
<filter-name>Filter1</filter-name>
<filter-class>com.imooc.project2.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

相关代码:

过滤器

package com.imooc.project2;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet Filter implementation class Filter1
*/
@WebFilter("/Filter1")
public class Filter1 implements Filter {

/**
* Default constructor.
*/
public Filter1() {
// 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 {
// TODO Auto-generated method stub
// place your code here

// pass the request along the filter chain
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
//当另一处登录的时候,对应的session对象被销毁;此时会使loginUser为null
String loginUser = (String)req.getSession().getAttribute("LoginUser");
String url = req.getRequestURI();

if(url.equals("/FirstProject/index.jsp") || url.equals("/FirstProject/") || url.equals("/FirstProject/save.jsp") ){
chain.doFilter(req, res);
}
else {
if(loginUser == null) {
System.out.println("a");
System.out.println(url);
res.sendRedirect("index.jsp?flag=1");

}
else chain.doFilter(req, res);}

}

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

}

相关代码:

缓存存放类

package com.imooc.project2;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

public class LoginCheck {
private static LoginCheck instance = new LoginCheck();
private Map<String,String>LoginSessionId=new HashMap<String,String>();
//key值:登录用户登录名,value值:登录用户sessionId
private Map<String,HttpSession>LoginSession=new HashMap<String,HttpSession>();
//key值:登录用户sessionId,value值:登录用户session对象
public LoginCheck() {}

public static LoginCheck getInstance() {
return instance;
}

public void setSessionIdByUsername(String username , String sessionId) {
this.LoginSessionId.put(username,sessionId);
}

public void setSessionById(String sessionId , HttpSession session) {
this.LoginSession.put(sessionId,session);
}

public String getSessionIdByUsername(String username) {
return LoginSessionId.get(username);
}

public HttpSession getSessionBySessionId(String sessionId) {
return LoginSession.get(sessionId);
}
}

相关代码:

​监听器

​package com.imooc.project2;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class LoginListener implements HttpSessionAttributeListener {

@Override
public void attributeAdded(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
//获取session属性值:也就是输入的账号
String userNumber = (String)event.getValue();
//获取session属性名;
String username = event.getName();
//获取当前session对象
HttpSession session = event.getSession();
//获取当前sessionId
String sessionId = session.getId();
//获取缓存的sessionId
String sessionId2 = LoginCheck.getInstance().getSessionIdByUsername(userNumber);
if(username.equals("LoginUser")) {

if(sessionId2==null) {}
else {
HttpSession session2 = LoginCheck.getInstance().getSessionBySessionId(sessionId2);
//撤销session
session2.invalidate();

}

}

LoginCheck.getInstance().setSessionById(sessionId, session);
LoginCheck.getInstance().setSessionIdByUsername(userNumber, sessionId);

}

@Override
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub

}

}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕小尤 2021-03-18 14:03:38

已完成练习,继续加油!

祝学习愉快!

  • rock221 #1

    问题1:老师,这样写的话,有一个小bug吧。

    if(url.equals("/FirstProject/index.jsp") || url.equals("/FirstProject/") || url.equals("/FirstProject/save.jsp") ){
    chain.doFilter(req, res);
    }

    当没有登录的时候,直接

    "/FirstProject/save.jsp"

    这个url,那么就放行了, 进入到这个页面了阿。 


    问题2:

    我自己测试了下,如果对这个保存账号信息的页面放行的话,并没有实现响应重定向阿。为什么呢?页面弹出了http://img1.sycdn.imooc.com//climg/6060075009e9481409220418.jpg


    代码如下

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>2-5作业</title>
    </head>
    <body>
    <div style="margin-left:40px;">
    <h1>系统登录</h1>
    </div>
    <form action="/servlet/login" id="form" method="post">
    <ul style="list-style-type: none">
    <li >用户名:</li>
    <li><input id="name" name="nm" style="width:200px;"></li>
    <li>密码:</li>
    <li><input type="password" id="password" name="password" style="width:200px;"></li>
    <li style="margin-top:10px;"><input type="submit" value="登录" id="btn"></li>
    </ul>
    </form>
    <script type="text/javascript">
    //创建登录事件:
    document.getElementById("form").onsubmit=function(){
    //正则表达式设置登录信息
    var regexN=/^[a-z|A-Z|0-q]{1,10}$/;
    var regexP=/^[a-z|A-Z|0-q]{1,10}$/;
    //获取登录和密码的value值
    var name=document.getElementById("name").value;
    var password=document.getElementById("password").value;
    //进行匹配
    if(regexN.test(name)==false){
    alert("用户名不符合当前格式!");
    return false;
    }else if(regexP.test(password)==false){
    alert("密码不符合当前格式!");
    return false;
    }else{
    alert("登录成功");
    return true;
    }
    }

    </script>
    </body>
    </html>
    package com.imooc.homework2;


    //2-5作业, 登录成功后存储账号信息到session,之后跳转到主页
    import java.io.IOException;

    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 javax.servlet.http.HttpSession;

    /**
    * Servlet implementation class LoginServlet
    */
    @WebServlet("/servlet/login")
    public class LoginSessionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
    * @see HttpServlet#HttpServlet()
    */
    public LoginSessionServlet() {
    super();
    // TODO Auto-generated constructor stub
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取信息前端账号,密码
    String name=request.getParameter("nm");
    String password=request.getParameter("password");
    //获取session对象
    HttpSession session=request.getSession();
    //把账号信息存到session中
    session.setAttribute("LoginUser", name);
    //响应重定向到主页;
    response.sendRedirect("/homepage.html");


    }

    }
    package com.imooc.homework2;

    import java.io.IOException;
    import java.util.List;

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

    //2-5作业,过滤器:
    public class LoginSessionFilter implements Filter {

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

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    //获取前端账号信息,在session中
    HttpServletRequest req=(HttpServletRequest)request;
    HttpServletResponse res=(HttpServletResponse)response;
    String loginUser=(String)req.getSession().getAttribute("LoginUser");
    //获取当前uri
    String uri=req.getRequestURI();
    System.out.println("本次获取的uri:"+uri);
    //进行判断
    if(uri.startsWith("/login")|| uri.startsWith("/servlet/login")) { //当访问的url开头为login的时候,不拦截,直接放行,进入到登录页面;
    chain.doFilter(request, response);
    //因为前端已判定过了。如果账号信息不对的话,是无法提交的,所以这里的name肯定是正确的信息;
    }else if(loginUser!=null){ //如果loginUser的值!=null的时候,说明登录成功了,跳转到主页;
    System.out.println("本次账号信息:"+loginUser);

    chain.doFilter(request, response);

    }else {
    //如果session中的账号(loginUser)等于空的时候,当另一处登录的时候,对应的session对象被销毁
    //或者当为登录的时候,
    res.sendRedirect("/error.html"); //拦截一切未登录的uri;

    }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub

    }

    }
    ​<?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>homework-listener</display-name>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <!-- Servletcontext 实现 -->
    <!-- <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.imooc.homework.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
    <listener-class>com.imooc.homework.LoginListener</listener-class>
    </listener>
    -->

    <!-- session实现过滤器 -->
    <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.imooc.homework2.LoginSessionFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    </web-app>


    2021-03-28 12:35:38
  • 同学你好,关于同学的问题:

    1、if中对/FirstProject/save.jsp"进行判断,如果直接访问/FirstProject/save.jsp",不会被拦截。

    2、测试同学的代码,可以重定向。web.xml中对所有的路径进行了拦截,如果不是以/login和/servlet/login的路径访问,会被重定向至/error.html,由于/error.html不被放行,则会一直被拦截,如:

    http://img1.sycdn.imooc.com//climg/60602dc409ab1b2204760310.jpg

    在同学的截图中,是访问/servlet/login,所以被放行了,在LoginSessionServlet类中的doGet()方法,向页面追加了“Served  at:”输出语句,如:

    http://img1.sycdn.imooc.com//climg/60602ec1093c479309070450.jpg

    建议同学有问题,新开一个问答描述。

    祝学习愉快~

    2021-03-28 15:23:52
  • 我下次重开一个问题。if中对/FirstProject/save.jsp"进行判断,如果直接访问/FirstProject/save.jsp",不会被拦截。不拦截放行了, 不就再没有登录的情况下,直接转到了主页了吗。?

    问2:我需要在响应重新向下面加个放行吧,不然死循环。 每次到这个响应一个新的请求,然后又死掉这里了

    2021-03-28 15:28:41
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师