如何在特定会话中跟踪特定浏览器的网站

时间:2017-03-13 12:36:42

标签: javascript java jsp cookies session-cookies

1.如何在同一浏览器的下一个标签中找到您的网站? 2.如何防止在第二个标签中打开网站?

1 个答案:

答案 0 :(得分:2)

如果浏览器首先调用您的站点,则在服务器端创建会话,从而将会话cookie发送到浏览器。在HTML中,您可以嵌入隐藏的表单值。每个后续调用都必须包含此隐藏值。最好是始终使用POST,以便隐藏值不包含在URL中。

如果用户打开第二个标签并想要打开您网站的网址,则不会包含隐藏参数,但第一个标签中的会话Cookie为。

因此,在服务器端,您知道已有会话但缺少隐藏值。所以你可以发送完全不同的回复。

<强>更新 这是一个小例子。

在网络内容文件夹中有一个子文件夹protected。所有包含的JSP文件只能在一个选项卡中打开。这里只有MyJsp.jsp

在根文件夹中有两个JSP:error.jsp当有人试图在第二个选项卡中打开受保护的JSP时显示。并index.jsp重定向到protected/MyJsp.jsp

并且有一个servlet过滤器映射到protected文件夹。在执行此文件夹中的JSP之前,将调用此过滤器。

protected/MyJsp.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <p>Hello,
    <c:choose>
    <c:when test="${not empty param.name}">
      <c:out value="${param.name}" />.
    </c:when>
    <c:otherwise>
      stranger.
    </c:otherwise>
    </c:choose>
  </p>
  <form method="post">
    <label>Please enter your name</label>
    <input id="name" name="name" type="text"/>
    <input id="marker" name="marker" type="hidden" 
        value="<c:out value="${sessionScope.marker}"/>"/>
    <button type="submit">OK</button>
  </form>
</body>
</html>

这个JSP要求一个名字。表单提交通过POST调用相同的JSP。隐藏字段填充了会话中的值。

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--include the library-->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="protected/MyJsp.jsp"/>

servlet过滤器:

@WebFilter("/protected/*")
public class OneTabFilter implements Filter {

  private static final String MARKER_NAME = "marker";
  private static final String MARKER_VALUE = "4711*0815";

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request; 
    final HttpServletResponse rsp = (HttpServletResponse) response;
    HttpSession session = req.getSession(false);
    if(session == null) {
      session = req.getSession(true);
      // Put the marker value into session so it is usable in JSP files.
      session.setAttribute(MARKER_NAME, MARKER_VALUE);
      // pass the request along the filter chain
      chain.doFilter(request, response);
    } else {
      if(MARKER_VALUE.equals(req.getParameter(MARKER_NAME))) {
        // pass the request along the filter chain
        chain.doFilter(request, response);
      } else {
        // Redirect to the error page.
        // The error page itself is not affected by this filter.
        rsp.sendRedirect(req.getServletContext().getContextPath() + "/error.jsp");
      }
    }
  }

  // ...
}

亲自试试!