背景:用戶登陸後才能訪問的頁面,在用戶沒有登陸時訪問要對其進行攔截(可以使用攔截器),這裏介紹一種標籤的方式攔截
使用步驟
- 定義標籤類
/* 定義標籤類(需要繼承SimpleTagSupport)*/
public class LoginTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
PageContext pageContext = (PageContext) super.getJspContext();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
HttpSession session = pageContext.getSession();
User login_user = (User) session.getAttribute("login_user");
if(login_user==null){
//利用response進行頁面間的響應,重定向到其他頁面
response.sendRedirect(request.getContextPath()+"/client/error.jsp");
}
}
}
- 在WEB-INF文件夾下定義對應的tld文件
<?xml version="1.0" encoding="utf-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<!-- 描述 自定義標籤版本的一種描述 -->
<description>Login tag</description>
<!-- 顯示的名稱 導包進行的一個展示 -->
<display-name>Login core</display-name>
<!-- 版本號 -->
<tlib-version>1.0</tlib-version>
<!-- 短名 -->
<short-name>hjy</short-name>
<!-- uri :導包 -->
<uri>http://hjy.login-tags</uri>
<!-- 定義一個標籤 -->
<tag>
<!-- 標籤名 -->
<name>login</name>
<!-- 標籤處理類 -->
<tag-class>com.bookstore.utils.LoginTag</tag-class>
<!-- 設置標籤爲空 -->
<body-content>empty</body-content>
<!-- 定義標籤的屬性 -->
<!-- 無-->
</tag>
</taglib>
- 在jsp頁面使用,使用前要引入標籤
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="pp" uri="http://hjy.login-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>電子書城</title>
</head>
<body class="main">
<pp:login />
<div>登陸後才能訪問的其他內容</div>
</body>
</html>