在js、css中嵌入java/jsp代码

推荐第一种方式:

一.css当做jsp文件使用。需要配置web.xml把css后缀的访问映射到jsp文件的解释者那里。

web.xml内容中增加下下面的servlet映射:

 

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
</web-app>  

 

注:名为jsp的servlet是tomcat容器自带的类:org.apache.jasper.servlet.JspServlet,用于翻译jsp文件,配置是在tomcat自带的web.xml里面。配置如上的映射后,css文件里面的jsp或java代码就能被tomcat解释了。你可能注意到了,这个方式只适合tomcat。至于其他的服务器,就要看它的jsp解释者是谁了,可以看看它的配置文件。

 

二.过滤url,css的后缀改成jsp。

servlet代码:

 

package pp.util;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CssAnalyserServlet
 */
public class CssAnalyserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CssAnalyserServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		System.out.println(this.getClass().getName()+":---------分析带java代码的cssj"+uri);
		String path = request.getContextPath();
		String uri2=uri.substring(uri.indexOf(path)+path.length(),uri.indexOf("cssj"))+"jsp";
		RequestDispatcher rd=request.getRequestDispatcher(uri2);
		rd.forward(request, response);
	}

}

 页面中引用css的样子如下:

<link rel="stylesheet" type="text/css" href="<%=basePath%>css/head.cssj">

这样head.jsp就被当做css返回了。

 

当然也可以不写servlet,而直接用:

<link rel="stylesheet" type="text/css" href="<%=basePath%>css/head.jsp">

 

js的情况类似。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值