今天打算模拟一个JSTL表达式出现的一个问题,结果想实现一种效果——先执行servlet之后再跳转到JSP页面
下面我简单介绍一下我实现的方式,使用的是——过滤器
过滤器:是可插入的web组件,拦截请求和响应,可以对请求和响应进行过滤(是在中间件中的东西tomcat\weblogic)
1、在web.xml中添加如下配置信息
<!-- 测试过滤器的使用方式 --> <filter> <filter-name>filterTest</filter-name> <filter-class>hb.servlet.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>filterTest</filter-name> <!-- 下面这个url一定要配置正确,因为在系统启动的时候会执行init()方法 --> <url-pattern>/filter/filter.do</url-pattern> </filter-mapping>
2、编写一个类继承Filter 接口,实现过滤器的功能
package hb.servlet.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.log4j.Logger; public class MyFilter implements Filter { private static Logger log = Logger.getLogger(MyFilter.class); public void destroy() { log.info("destroy filter"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException { log.info("doFilter filter"); request.setAttribute("abc", "huangbiao"); RequestDispatcher rd = request.getRequestDispatcher("/filter/filterTest.jsp"); rd.forward(request, response); } public void init(FilterConfig filterConfig) throws ServletException { log.info("init filter"); } }
3、在URL地址栏中输入 http://localhost:8080/dbpool/filter/filter.do
每次输入上面的地址都会执行doFilter()方法里的内容
在JSP页面中使用EL表达式将内容显示出来
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'filterTest.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> filterTest.jsp<br> <%=request.getAttribute("abc") %><p> <textarea name="textarea" style="width:100%; height:125px;" id="textarea" readonly="readonly"> <c:choose> <c:when test="${abc != null}"><%=request.getAttribute("abc") %></c:when> <c:otherwise></c:otherwise> </c:choose> </textarea> <br> <div><textarea name="textarea2" style="width:100%; height:125px;" id="textarea2" readonly="readonly"><c:choose><c:when test="${abc != null}"><%=request.getAttribute("abc") %></c:when><c:otherwise></c:otherwise></c:choose></textarea></div> </body> </html>
会发现一种很奇怪的现象,两种textarea标签里面的内容不一样
因此,在使用JSTL逻辑控件的时候,尽量不要换行,不然会出现一些意想不到的效果