开发者

Ways to change HTML string received from Java

开发者 https://www.devze.com 2023-03-17 07:27 出处:网络
I understand that ideally HTML string should always be in JSP and not returned from Java file..But in my app, my JSP receives HTML string from Java class..

I understand that ideally HTML string should always be in JSP and not returned from Java file..But in my app, my JSP receives HTML string from Java class..

My question is can I modify that string dynamically or by some code in JSP..

E.g. based on certain condition in JSP, can i convert a 3-column table s开发者_高级运维tructure into a 2-col structure..in other cases, it would continue as returned by the Java class..

Thank you.


You can certainly do it in Java. If your HTML string is in valid XML, you can use XML manipulation for that.

Another option might be to use Javascript, and change the HTML on the client. jQuery makes it very easy.

Ideally though, you'd have a better separation of concerns in your application. Your Java class that returns HTML should really only return the essential information contained in that HTML, and let its callers decide on the representation of that information.


If you're doing things properly, you should always be able to alter layout using CSS. Your difficulties stem from the fact that you're receiving HTML from a service, which should never know or care about presentation, and it's written in such a way that layout is fixed.

If CSS won't do it, you can always use JavaScript and a good library like jQuery to alter the DOM in the page, but you'll hate yourself when it comes to maintenance.


The essence of what you are asking is the JSP variable. A JSP variable is denoted as

<%=varName%>

If we had the class

package com.blessedgeek.lyrics.server;

public class BengawanSolo {

  public String title = "Bengawan Solo";
  public int numCols = 1;
  public String[]
    ml = {
      "Bengawan Solo",
      "Riwayat mu ini",
      "Sedari dulu jadi",
      "perhatian insani"
      },

    en = {
      "Bengawan River",
      "Thus your history",
      "From of old you have been",
      "Of human/sentient attention"
    },

    he ={
      "הנהר בנגעון",
      "הקיום שלך",
      "מהזמנים המוקדמים אתה הפכה",
      "מוקד החיים"
    }
  ;

  public String[][] columns = {ml, en, he};

}

It has first stanza of the lyrics for an Indonesian folk song of the Solo River in Java, Indonesia. You have the user specify a choice of three HTML layouts

  1. One column with the original Indonesian lyric
  2. Two columns: Column 0 = Indonesian, Column 1 = English translation
  3. Col 0 = Indonesian, Col 1 = English transl, Col 2 = Hebrew transl

.

<jsp:useBean class="com.blessedgeek.lyrics.server.BengawanSolo" id="lyric"/>
<html>
<head>
<title><%=lyric.title%></title>
</head>
<body>

<table>
  <%
  int numCols = lyric.numCols;
  try{
    String numColsParam = request.getParameter("numCols");
    if(numColsParam!=null)
      numCols = Integer.parseInt(numColsParam);
  }
  catch(Exception e){}

  for (int row=0; row<lyric.ml.length; row++){
    %><tr><%
      for(int col=0; col<numCols; col++){
        %><td><%=lyric.columns[col][row]%></td><%
      }
    %></tr><%
  }
  %>
</table>

</body>
</html>

Therefore, in order to conveniently vary the number of columns and rows, the data supplied by the JSP bean class should be in an array or a numerically addressable vector/list.

Further, you might wish to perform Perl, python style of multi-line string variable definition, which unfortunately Java would not currently allow you to do:

String query ="
SELECT <%=columns%>
FROM Lyrics
WHERE title="Bengawan Solo"
";

But, never mind Java's multi-line unfriendliness. I have a multi-line JSP custom tag to overcome this weakness.

Text Custom Tag - how to use

<%@ taglib
uri="/WEB-INF/text-taglib.tld" prefix="hello"%>

<hello:text id="query" scope="session">
    SELECT <%=columns%>
    FROM Lyrics
    WHERE title="Bengawan Solo"
</hello:text>

The id query is actually transmuted (trans-mutated) from session/request/page attribute into a StringBuffer java variable "query". So that you could code

StringBuffer anotherQuery = query;

Or perform regex directly on query.

Or you could append to query by using "ref" instead of "id". "id" defines the variable. "ref" continues the usage of an already defined StringBuffer variable.

<hello:text ref="query" scope="session">
  AND stanza = 1
</hello:text>

You could of course define the StringBuffer "query" using usual Java declaration first and then use "ref" to continue its reference without initiating it with an "id".

Text custom tag example

    <jsp:useBean class="com.blessedgeek.lyrics.server.BengawanSolo" id="lyric"/>

    <html>
    <head>
    <title><%=lyric.title%></title>
    </head>
    <%
      int numCols = lyric.numCols;
      try{
        String numColsParam = request.getParameter("numCols");
        if(numColsParam!=null)
          numCols = Integer.parseInt(numColsParam);
      }
      catch(Exception e){}

      String[][] queryResults = yourDbQuerier.submit(query.toString());
    %>

    <body>

The text custom tag is useful when you need to embed java codelets into the block. You might wish to place emphasis on phrases:

    <hello:text id="sheet" scope="session">
    These are the lyrics to the song "<%=title%>.
    If you like it jump <%=numCols%> times.

    <table>
      <%

      for (int row=0; row<queryResults[0].length; row++){
        %><tr><%
          for(int col=0; col<queryResults.length; col++){
            String line = queryResults[col][row];
            int k = line.replaceAll("riwayat", "<b>riwayat</b>");
            %><td><%=line%></td><%
          }
        %></tr><%
      }
      %>
    </table>
    </hello:text>

And output the content of "sheet" into the JSP's html response:

<%=sheet%>
</body>
</html>

Creating templates from existing files.

This text custom tag has been very useful when I needed to concoct a complete text file as input into a mainframe legacy application to extract and massage output as response for a web service. Where the input of the mainframe app had traditionally been human/spreadsheet/machine constructed with variable number of columns and rows of input. There are various formats of inputs, too many to count.

Therefore, it allows me to quick-and-dirty copy existing sample files from each format as template and then I insert whatever code necessary to allow session specific variation. Because I really dislike translating those huge files into thousands of discontinuous String variable declarations.

(hello, hello gods of Java when will multi-line string declaration be available, hello hello knock knock, any response??).

Refer to my blog post to download the custom tag from google code: http://h2g2java.blessedgeek.com/2009/07/jsp-text-custom-tag.html

0

精彩评论

暂无评论...
验证码 换一张
取 消