简体   繁体   中英

Including a page with JSP and loading various CSS files

I have a .jsp file with structure of a page (lets call it base.jsp), it also includes link to CSS file (base.css). Now I want to include this base.jsp in another jsp file, pass some parameter and according to this parameter load additional CSS file. It should be something like that (I know this code is incorrect, I just want to demonstrate what I want to achieve eventually):

<%@include file="base.jsp" x="720" %>
if(x == "720")
    load 720.css
else if(x == "460")
    load 460.css
else
    load 320.css

How can it be done?

Edit

Perhaps it can be done with something like that?

<%@include file="base.jsp?x=720" %>

and then somehow read this x parameter in the base.jsp file and load additional css accordingly? Is there such possibility?

Please put the following code in head tag of the base.jsp

<%
        String size = request.getParameter("size");
        if(size == null)
            out.println("<link rel='stylesheet' href='base.css'>");
        else if(size.equals("720"))
            out.println("<link rel='stylesheet' href='720.css'>");
        else if(size.equals("460"))
            out.println("<link rel='stylesheet' href='460.css'>");
        else if(size.equals("320"))
            out.println("<link rel='stylesheet' href='320.css'>");

%>

and put the following code on another jsp which include base.jsp

<jsp:include page="base.jsp">
    <jsp:param name="size" value="720"/>
</jsp:include>

I would do it like this:

In the base jsp i could declare a method, which can receive an int parameter (the size)

Something like this:

<%! public String getSize (int x) {
String s;
if (x==720){
s="720.css";
else if(x==480){
s="another.css"}
//
return s;
}
%>

After at the include stage:

<% String s=getSize(720); %>
<%@include file="base.jsp">
<link rel='stylesheet' href='<%=s%>'>

Of course you can use Java snippets using "<%" and "%>" tags. But it is not a good practice to use Java snippet in JSP.

It will be better to use JSP tags for this purpose. You can use

<c:if test="${param.x == 720}">
    <link rel="stylesheet" type="text/css" href="720.css" />
</c:if>
<c:if test="${param.x == 460}">
    <link rel="stylesheet" type="text/css" href="460.css" />
</c:if>

Do not forget to include

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

in the beginning of jsp file, also add JSTL library to your project.

You can see some samples using JSP if tag in this URL. http://www.tutorialspoint.com/jsp/jstl_core_if_tag.htm

The full JSP page with the sample I have placed in this URL: http://pastebin.com/qn2Qh3GK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM