JSP的ContextPath刚写JSP的小伙伴基本都会遇到一个问题,就是卧槽我的静态文件为毛找不到啊,因为你首先必须设定ContextPath啊,骚年,下面给出一个例子。<% String path
JSP的ContextPath
刚写JSP的小伙伴基本都会遇到一个问题,就是卧槽我的静态文件为毛找不到啊,因为你首先必须设定ContextPath啊,骚年,下面给出一个例子。
<% String path = request.getContextPath(); String title="hehe";String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %><!-- 在文件的开始处加上上述语句 --><link type="text/css" rel="stylesheet" href="<%=basePath %>/static/style/common.css">
JSP的模板继承
JSP2.0的自定义tag使得模板继承成为了可能,下面我们先给出一个例子。
首先模板文件。
<%@tag description="Instructipn Template" language="java" pageEncoding="UTF-8"%><%@attribute name="content" fragment="true" %><%@attribute name="title" fragment="true" %><% String path = request.getContextPath(); String title="hehe";String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %><html> <%@include file="/views/widgets/head.html" %> <body> <%@include file="/views/widgets/topbar.html" %> <%@include file="/views/widgets/navbar.html" %> <div id="content"> <jsp:invoke fragment="content" /> </div> <%@include file="/views/widgets/footer.html" %> </body></html>
然后给出一个jsp文件继承该模板
<%@page contentType="text/html" language="java" pageEncoding="UTF-8" %><%@taglib prefix="t" tagdir="/WEB-INF/tags" %><t:instruction> <jsp:attribute name="content"> <h1>呵呵</h1> </jsp:attribute> <jsp:attribute name="title"> hehe </jsp:attribute></t:instruction>
这里面有几点要注意:
- 使用这种方法做模板继承会导致某些css失效,主要是你的CSS 选择符不能被fragment截断,比如 .instruction .ctn .ctn_left这样的,instruction在模板文件里,而 ctn_left在fragment里,CSS就会失效
- 在模板文件中必须先定义jsp:attribute之后,才能在具体位置里用jsp:invoke设定
- 模板文件必须在/WEB-INF/tags目录下,不然会报错,有点奇怪,至今理解不能
- include的路径可以是相对的,也可以是绝对的,绝对路径的根目录在web-app
- 注意jsp:include 和 %include的区别,一个是先生成servlet转换为html后再拼接,而后者是先拼接再转换为html
由于静态引入的这个特性,我们还可以在引入文件里指定fragment,真是爽歪歪啊。。。当你在被引入的文件里访问父文件的变量时,eclipse会善意的帮你打上红X,所以不妨把引入的静态文件使用HTML后缀。
JSP的中文乱码问题
中文乱码的问题确实是比较头疼的,难道JSP这帮人都不鸟中国开发者么?一般的解决方案是在jsp文件头部加上一句
<%@page contentType="text/html charset=UTF-8" language="java" pageEncoding="UTF-8" %>
这样做的话你引入的每个文件都得加上这样几句,实在太特么恶心了。。
所以你可以在你的WEB.XML文件里加上这么一句。
<jsp-config> <jsp-property-group> <url-pattern>*.html</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group> </jsp-config>
总结
说了这么多,JSP真是个大坑啊。。。话说我觉着前后端分离是历史的必然,jsp也无法重回巅峰了。。。突然有点伤感啊,毕竟毕业季了。。。