WhiteSpace Form TextBoxes - java

I am repopulating a form field that a user previously filled out with Sessions in HTTP. I am grabbing the fields from the form through a servlet:
//On servlet
String polyNum = request.getParameter("policyNum")
session.setAttribute("policyNum", polyNum);
//On JSP
<td align = "right"><font color = "#FF0000">*</font><font face= "Calibri, Arial" size = "3"> Policy #:</font></td>
<td><input type="text" name= "policyNum" size="19" tabindex = "1" value="
<% out.println(session.getAttribute("policyNum");%>">
The Problem: When I run my JSP page, I get a leading whitespace in the textboxes of the form. Therefore, anytime I submit the form, whitespace is inserted into the database as well.
Any ideas? Any help would be greatly appreciated.

You can trim it like this:
String polyNum = request.getParameter("policyNum");
polyNum = polyNum == null ? null : polyNum.trim();
session.setAttribute("policyNum", polyNum );
and if your jsp looks like
<input type ="text" value="
<%= session.getAttribute( "policyNum" ); %>
"/>
you will get whitespace.
Also you don't show where you are inputting into the database.

Take a look at the .trim() method in the String class:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#trim()
"Returns a copy of the string, with leading and trailing whitespace omitted."

The Apache Commons StringUtils library is good for trimming as it handles nulls.
So
String polyNum = request.getParameter("policyNum");
polyNum = polyNum == null ? null : polyNum.trim();
Can become
String polyNum = StingUtils.stripToEmpty(request.getParameter("policyNum"));

It turned out that my scriplets within my jsp pages were placed syntanically wrong. I didn't need to trim whitespace after all. My forms are working fine now.
Your solution about the Apache library is interesting Damo. I appreciate your feedback.

Related

How to pass a variable's value form a Java Class to JSP?

I am calling a web service in which I need to shows some messages in a jsp page based on some conditions. I need to show the value of this variable in a JSP if it is not null. Looks like it is not working at all.
Is there any other way to achieve this?
Java
private String emailValidationMessage;
public String getEmailValidationMessage() {
return emailValidationMessage;
}
public void setEmailValidationMessage(String emailValidationMessage) {
this.emailValidationMessage = emailValidationMessage;
}
if( validateEmailAddressResponse.isVerifiedEmailDomain() == false &&
validateEmailAddressResponse.isVerifiedEmailFormat() == false ) {
setEmailValidationMessage( UiIntegrationKeyConstants.EMAIL_VALIDATION_CODE_EE01 );
}
JSP
<div>
<table width=100%>
<tr>
<c:if test="${emailValidationMessage != null}">
<td class="fieldLabelBold" style="color:#0033CC" align="center">${emailValidationMessage}</td>
</c:if>
</tr>
</table>
</div>
Am I doing it in a wrong way? I don't want to pass it as a URL param.
Thanks...
Yes there are other ways to achieve this,
1.El expression is one of this to achieve this.
2.You can use to set the values in sessions,
session.setAttribute("sessionName""someValue");
and call it in your JSP page as
String value = (String)session.getAttribute("sessionName") == null ? "":(string)session.getAttribute("sessionName");
,here you will get the value from session.Check whether it is null or not! It it is null,don't show,if else,show value.
You can use two ways to display,1.Using Expression tags<%=%> or using javascript/jquery, by setting the value to the respected tags using their own id. For Javascript and for Jquery. Using jquery/javascript,you can give additional effects as well.Hope this may help.Thankyou.

How to remove all tag from xml file using java/Scala?

I have xml content as
<p/>
<p>Highlighted Applications</p>
<p/>
<table>
<tbody>
<tr> <td>
<p>Projects </p>
</td> <td>
<p>Description</p>
</td>
</tr>
<tr> <td>
<p>VNC login for Windows Mobile devices</p>
</td> <td>
It may have custom tag, which I don't know in advance. Is it possible to get text from above xml without walking xml-tree and removing each tag one by one in java/scala. I came across this, but this is to remove unnecessary tag not removing all tag? I am looking for some generic kind of solution, which can remove all tag or get all text from xml.
Required Output:
Highlighted Applications
Projects
Description
VNC login for Windows Mobile devices
I'm open to any other approach/library suggestion?
If you can get all the content of your xml file as a String i would suggest this way :
You can use replaceAll with regex \<.*?\> like this :
str.replaceAll("\\<.*?\\>", "")
to replace all the empty line you can use :
str.replaceAll("(?m)^[ \t]*\r?\n", "")
You can take a look about this here remove all empty lines
the output in the end should look like :
Highlighted Applications
Projects
Description
VNC login for Windows Mobile devices
The correct way to do it is something like this:
def extractText(nodes: Seq[xml.Node]): Seq[String] = nodes.flatMap {
case xml.Text(t) => Seq(t)
case n => extractText(n.child)
}
Then you can do
extractText(xml.XML.loadString(xmlToParse))
.filter(_.matches(".*\\S.*"))
.mkString("\n")
Regex, as the other answer suggests (you don't need to escape < and > with backslashes BTW, and also \s is a metacharacter you can use instead of enumerating all possible whitespace symbols), is a simpler solution, that will work most of the time, but break down on some corner cases.
For the purists, here is also a tail-recursive version (helps particularly if your document structure is really-really-really deep :))
#tailrec
def extractText(nodes: Seq[xml.Node], result: List[String] = Nil): Seq[String] = nodes match {
case Seq() => result.reverse
case Seq(xml.Text(t), tail#_*) => extractText(tail, t :: result)
case Seq(head, tail#_*) => extractText(head.child ++ tail, result)
}
Using Jsoup#text
Gets the combined text of this element and all its children. Whitespace is normalized and trimmed.
For example, given HTML <p>Hello <b>there</b> now! </p>, p.text() returns "Hello there now!"
String s = //..html code
System.out.println(Jsoup.parse(s).text());

escaping = character in java string

Iam formating my question. Sorry for this. Here is the summary of my question
in JSP I have a field
<input maxlength="200" name="productName" >
I enter value like "cQN==ujyRMdr+Qi8dO9Xm*eRun+ner==aLTyt?aKmGI"
In Action
public String getXMLObject(HttpServletRequest request) throws Exception
{
URLDecoder decoder = new URLDecoder();
String productName = decoder.decode(productLicenseKey ,"UTF-8");
System.out.println("-->ProductNameAction---->getXMLObject--->productName --> : "+productName);
}
Iam getting output as "cQN==ujyRMdr Qi8dO9Xm*eRun ner==aLTyt?aKmGI".
If you observe + is converting to space which I don't want.
If I won't use decoder.decode other characters are converting to the respective escape chars. But I want as it is in the Action class
code how iam and retrieving value
in JSP I have a field
I enter value like "1012990-c1e197eda0s-a1de198b0b2-819e25307de-xnXrmXWBidhksyn70rGyTHa==cQNujyRMdrQi8dO9Xm+eRunERd==aLTyt+aKmGI+KRCcRtmP5ehfR=="
In Action
private String saveProductName( SWHttpServletRequest request)
throws Exception
{
try
{
String ProductName = request.getParameter("ProductName");
System.out.println("-->ProductAction---->saveProductName--->ProductName --> : "+ProductName);
}
}
Iam getting output as "1012990-c1e197eda0s-a1de198b0b2-819e25307de-xnXrmXWBidhksyn70rGyTHa%253D%253DcQNujyRMdrQi8dO9Xm+eRunERd%253D%253DaLTyt+aKmGI+KRCcRtmP5ehfR%253D%253D"
If we use decoder except + everything is working fine
You shouldn't have to decode anything in the action. The servlet api does that for you. request.getParameter() is sufficient. The problem is that you didn't properly encode the parameter when generating the form field or URL.
If it's a form field, then it's part of HTML code, and thus must be HTML-escaped:
<input type="hidden" name="someName" value="<c:out value="${theFieldValue}"/>"/>
The struts html:hidden also takes care of html-escaping properly.
If it's a URL, then it should be url-encoded, and html-escaped:
<c:url var="theUrl" value="someUrl.do">
<c:param name="someName" value="${theFieldValue}"/>
</c:url>
The link text
If you type this value in a text field of a form, then request.getParameter() is sufficient.

String is saved wierdly in html hidden input

I have a String like follows which is coming from server side
String productIDs = "[{"productID":"226167","productName":"It is my life (Bingo)"},{"productID":"3193","productName":"It is your name (jingo)"},{"productID":"273838","productName":"It's the same milk/Butter i drink/ate yesterday"}]"
Now I am saving it in a hidden input field this string
<input type="hidden" class="hiddenInput" value="<%=productIDs %>" />
But when i checked it through firebug it is saved very wierdly as follows
<input type="hidden" class="hiddenInput" yesterday"}]"="" is ="" my ="" Butter ="" life ="" (Bingo)"},{"productid":"273838","productname":"It ="" crmo="" (paar)"},{"productid":"3193","productname":"It ="" milk="" same ="" flip-off="" productid":"226167","productname":"It ="" value="[{" />
Anybody has got any idea why this is happening?
Problem is with the way you're saving the string, you have to switch the type of quotes you use otherwise js doesn't know where the string ends and starts.
In your question it would look like this:
String productIDs = "[{'productID':'226167','productName':'It is my life (Bingo)'},{'productID':'3193','productName':'It is your name (jingo)'},{'productID':'273838','productName':'It's the same milk/Butter i drink/ate yesterday'}]"
You can also use \" instead of ' but that, to me, is alot more confusing.
Edit
You can do this using the following code:
strUWantToChange.replace('"',"'");
If you have quotes in your String, you need to escape them before pasting it into HTML.
As already said by other answers, quotes must be escaped. These are not the only characters that should be escaped. <, >, ' and & should systematically be escaped in HTML. The risks are
invalid HTML
broken page
XSS attacks and security vulnerabilities
Whenever you must display data for which you're not absolutely sure that it doesn't contain any of such characters (for example : data coming, directly or indirectly, from the user, free textual data in general), escape this data.
This is done, in JSP by two simple constructs:
the JSTL <c:out> tag:
the JSTL fn:escapeXml EL function: ${fn:escapeXml(productIDs)}
Scriptlets should not be used for years in JSP. Use the JSTL, other custom tags, and the EL.
Try this:
String productIDs = "[{\"productID\":\"226167\",\"productName\":\"It is my life (Bingo)\"},{\"productID\":\"3193\",\"productName\":\"It is your name (jingo)\"},{\"productID\":\"273838\",\"productName\":\"It's the same milk/Butter i drink/ate yesterday\"}]";

getting hidden fields value

I am working on a Struts2 application. I am setting the value of a hidden field in JSP with the purpose to access it by JavaScript.
My JSP code:
<s:iterator value="collegelist">
<tr>
<td align="center"><s:property value="collegename"/></td>
<s:hidden name="hiddenname" key="collegename" />
</tr>
</s:iterator>
My JS code:
var myForm = document.frmAction;
var text = myForm.hiddenname.value;
alert("hidden field text is:" + text);
The alerts shows a blank value.
What is the cause and how can I solve this?
Try
element = document.getElementsByName("hiddenname");
alert(element[0].value);
You generate multiple fields having the same name, since your code is inside a s:iterator tag. You should obviously have such a loop in your Javascript as well :
var hiddenFields = document.getElementsByName("hiddenname");
for (var i = 0; i < hiddenFields.length; i++) {
alert("hidden field text is::" + hiddenFields[i].value);
}
Also, verify the the value is not blank in the generated HTML, and that the hidden fields'a name is hiddenname.
I tried your code and it surely works.. problem is somewhere in your server code itself..
Look here: http://jsbin.com/ajajo4/2/edit
Make sure you have only one form with the name "frmAction" and only one hidden field with the name "hiddenname". If you have multiple, you'll get an array instead of a single value.
The root of the problem is that you are inside of an iterator. Struts updates the name for you in order to correctly hook everything up. If you pull up your page and view source, your hidden field will probably look something like this:
<input type="hidden" name="collegelist[0].hiddenname" value="thename"/>
Regardless, if you want the retrieval by name to work, do not trust the name that you supply to a struts tag. Always pull up the generated source and look at what name the field actually has.

Categories

Resources