如果浏览器首先调用您的站点,您会在服务器端创建一个会话,从而将会话 cookie 发送到浏览器。在您的 HTML 中,您可以嵌入隐藏的表单值。这个隐藏值必须包含在每个后续调用中。最好是始终使用 POST,这样隐藏的值就不会包含在 URL 中。
如果用户打开第二个选项卡并希望打开您网站的 URL,则不包含隐藏参数,但第一个选项卡中的会话 cookie 包含在内。
所以在服务器端你知道已经有一个会话但是隐藏的值丢失了。因此,您可以发送完全不同的响应。
更新
这是一个小例子。
在网页内容文件夹中有一个子文件夹protected。所有包含的 JSP 文件只能在一个选项卡中打开。这里只有MyJsp.jsp。
在根文件夹中有两个 JSP:error.jsp,当有人试图在第二个选项卡中打开受保护的 JSP 时显示。和index.jsp 重定向到protected/MyJsp.jsp。
还有一个映射到protected 文件夹的servlet 过滤器。此过滤器将在执行此文件夹中的 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");
}
}
}
// ...
}
自己试试吧!