concatenating strings and variables - java

i have problems while concatenating strings and variables. I tried to add quotes and slashes, i tried to move them back and forth, but i wasnt able to find a solution.
I have a class that 'write' a div. I wrote this
String var = "width:100px";
String div ="<div class=\"divClass\" style="+var+">";
The code i wrote give me
<div class="divClass" style=width:100px>
But, in order to write a good code i would need this
<div class="divClass" style="width:100px">
with the value of style between quote "".

You need to escape the " symbol
String var = "\"width:100px\"";
String div ="<div class=\"divClass\" style="+var+">";
Then div would be
<div class="divClass" style="width:100px">
The reason we need to do this is that we need to tell the compiler that the quotes symbol " is a part of the String and we are not closing the String literal yet.
Example
System.out.println("hello"); => hello
System.out.println("\"hello\""); => "hello"
When the compiler sees \" it reads \ and knows that it has to ignore the next character ie ".

try
String var = "\"width:100px\"";
as you will need to escape your quotes

Just try like this.
String var = "width:100px";
String div ="<div class=\"divClass\" style=\""+var+"\">";

Related

How to insert HTML code in a context variable with thyme leaf [duplicate]

I'm using Thymeleaf to process html templates, I understood how to append inline strings from my controller, but now I want to append a fragment of HTML code into the page.
For example, lets stay that I have this in my Java application:
String n="<span><i class=\"icon-leaf\"></i>"+str+"</span> \n";
final WebContext ctx = new WebContext(request, response,
servletContext, request.getLocale());
ctx.setVariable("n", n);
What do I need to write in the HTML page so that it would be replaced by the value of the n variable and be processed as HTML code instead of it being encoded as text?
You can use th:utext attribute that stands for unescaped text (see documentation). Use this with caution and avoid user input in th:utext as it can cause security problems.
<div th:remove="tag" th:utext="${n}"></div>
If you want short-hand syntax you can use following:
[(${variable})]
Escaped short-hand syntax is
[[${variable}]]
but if you change inner square brackets [ with regular ( ones HTML is not escaped.
Example within tags:
<div>
[(${variable})]
</div>

String where from JSP is doesn't work at JavaScript

<%for (String st : geocodePhoto.keySet()) {%>
alert(<%=st%>); // not work
alert(<%=geocodePhoto.get(st).getX()%>); // work fine
alert(<%=geocodePhoto.get(st).getY()%>); // work fine
alert(<%=geocodePhoto.get(st).getDate()%>); // not work
<%}%>
getX is return double value and getDate return String value like 'yy:mm:dd hh:mm:ss'
st has same form 'yy:mm:dd hh:mm:ss'
2,3 line alert is work fine but 1,4 line alert is doesn't work
what is wrong?
The <%= %> tag in JSP acts as if it calls String.valueOf() with the expression in the tag as the parameter, and writes the returned value to the output. So, your generated JavaScript source probably looks something like this:
alert(13:11:23 10:30:17);
alert(-0.06);
alert(51.5);
alert(13:11:23 10:30:17);
You're trying to pass text to the first and last calls to alert, but you aren't putting the text in quotes - so, you're getting a syntax error. The middle two calls are writing numbers into your JavaScript source - as a numeric constant is valid JavaScript, they work without being quoted.
So, your JSP code should look like this:
alert("<%=st%>");
alert(<%=geocodePhoto.get(st).getX()%>);
alert(<%=geocodePhoto.get(st).getY()%>);
alert("<%=geocodePhoto.get(st).getDate()%>");
Pass string through ""
alert("<%=st%>");
alert("<%=geocodePhoto.get(st).getDate()%>");

Escape characters in JQuery containing Java Codes

I'm working with JSP pages, and I need to append some HTML and Java codes inside a DIV, I only remember that I should escape " like this \", but I don't know about the other characters and I don't know if all non-letter characters should be escaped, here is the String.
String s ="<% ResultSet joinedRooms = myJavaDB.updateJoinedRooms(loginBean.getId());
while(joinedRooms.next()){%> <div id="<%=joinedRooms.getString(1)%>" class="chatRoom">
<div class="chatRoomName"><%=myJavaDB.getRoomName(joinedRooms.getInt(1))%></div></div><% } %>"
No need to roll your own, take a look at Apache Commons StringEscapeUtils.

JSP Text Processing with Regex

I have a large number (>1500) of JSP files that I am trying to convert to JSPX. I am using a tool that will parse well-formed JSPs and convert to JSPX, however, my JSPs are not all well-formed :)
My solution is to pre-process the JSPs and convert untidy code so the tool will parse them correctly. The main problem I am trying to resolve is that of unquoted attribute values. Examples:
<INPUT id="foo" size=1>
<input id=body size="2">
My current regex for finding these is (in Java string format):
"(\\w+)=([^\"' >]+)"
And my replacement string is (in Java string format):
"$1=\"$2\""
This works well, EXCEPT for a few patterns, both of which involve inline scriptlets. For example:
<INPUT id=foo value="<%= someBean.method("a=b") %>">
In this case, my pattern matches the string literal "a=b", which I don't want to do. What I'd like to have happen is that the regex would IGNORE anything between <% and %>. Is there a regular expression that will do what I am trying to do?
EDIT:
Changed to title to clarify that I am NOT trying to parse HTML / JSP with regexes... I am doing a simple syntactic transformation to prepare the input for parsing.
If a sentence contains an arbitrary number of matching tokens such as double quotes, then this sentence belongs to a context-free language, which simply cannot be parsed with Regex designed to handle regular languages.
Either there could be some simplification assumptions (e.g. there are no unmatched double quotes and there is only a certain number of those etc.) that would permit the use of Regex, or your need to think about using (creating) a lexer/parser for a case of context-free language. ANTLR is a good tool for this.
Based on the assumption that there are NO unquoted attribute values inside the scriptlets, the following construct might work for you:
Note: this approach is fragile. Just for your reference.
import java.util.regex.*;
public class test{
public static void main(String args[]){
String s = "<INPUT id=foo abbr='ip ' name = bar color =\"blue\" value=\" <%= someBean.method(\" a = b \") %>\" nickname =box >";
Pattern p = Pattern.compile("(\\w+)\\s*=\\s*(\\w+[^\"'\\s])");
Matcher m = p.matcher(s);
while (m.find())
{
System.out.println("Return Value :"+m.group(1)+"="+m.group(2));
}
}
}
Output:
Return Value:id=foo
Return Value:name=bar
Return Value:nickname=box

Escape sequence in java

I need to use regular expression with a string from a rss feed. It is following string.
private String text = "<![CDATA[<table border="0" cellspacing="0" cellpadding="6px"> <tr><td valign="top" align="center" width="150px"><img src="http://static.desktopnexus.com/thumbnails/978620-thumbnail.jpg" border="1" style="border: 1px solid #000000;"><br><strong>Princess,Aurora,Sleeping,Beauty</strong></td><td valign="top" style="font-size: 10pt;">A new wallpaper has been posted to the Entertainment gallery on Desktop Nexus.<br><br>Uploaded By: Jessowey<br>Category: Movies<br>Date Uploaded: 02/23/12<br>Native Resolution: 1024x768<br>Points: +1<br>Download Count: 0<br><br><b>View This Wallpaper Now</b></td></tr></table>]]>";
As you can see there are " inside the string, so I can't use it as a statement. I tried to use raw string but as you know it is not possible in java.
How can I extract img tag from the above statement. I need to do it programatically.
Thanks in advance!
It's very, very difficult (in general) to use regular expressions to parse XML/HTML, there is another post which lists good XML parsers for Java and their strengths, I suggest you use one of these.
If you wnat to use " in String literal in java you have to escape them with backslash like that
String stringWithParenthesis = "text \"in parenthesis\" out ";
Use \" in a string to use the " inside it. For example:
String yourFeed = "My so \"called\" String";
This works for some other special character like the backslash itself:
String antoherFeed = "Hello \"World\", what a nice \\ day \\ ";
You can parse your RSS-FEED for such special characters. Like in this question:
JAVA: check a string if there is a special character in it
and format them to valid string characters.

Categories