1) Purpose:
Dynamically generate css statements in jsp, and then output them to the browser for parsing and rendering.
2) The basis for the browser to parse the file:
After the page is loaded, the browser will initiate various requests to download various resources.
For example, download the css file and then parse the document according to the css parsing rules. If the Content-Type of the downloaded file does not match, the browser will automatically block it.
After knowing the browser’s parsing rules, all jsp needs to do is to disguise its own Content-Type into "text/css".
index.html
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>jsp文件输出为css文件</title> <link type="text/css" rel="stylesheet" href="./css.jsp" /> </head> <body> <p class="demo">wall say: hello!</p> </body> </html>
css.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false"%> <% // 伪装响应的http头部 response.setHeader("Content-Type", "text/css"); // 输出css样式 out.clear(); out.print("@charset \"utf-8\";\n"); out.print("p{color:red;}\n"); %>
The jsp was successfully disguised as a css file, and the browser parsed the style successfully!
For example, if it is disguised as js, set the Content-Type to "application/x-javascript"