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.
Related
So I'm a little unclear on how to properly use #PathVariable in the context I'm trying to here. Let me explain.
I have a JSP page with a table. The table contains all the records in a table in my database. That all works fine.
At the bottom of the table, there are buttons. Add, Edit, Delete. They are all using separate forms because I want to have separate URL paths/ HTTP Methods for each.
To accomplish this, I'm using JQuery so that when I hit submit on the form, it retrieves the ID value of the currently selected record. All of that works perfectly, and is not what I'm asking about.
Here is the form where the submit action is taking place:
<form:form id="editForm" action="./${courseId}.html" path="courseId" method="get">
<input type="hidden" id="editCourseId" name="courseId"/>
<input class="btn btn-lg btn-default btn-shadow" type="submit"
value="Edit"/>
</form:form>
So, what I want is for this form to call a URL with courseId as the #PathVariable value. The value of courseId is contained in the hidden input field with the name courseId. Again, that input field's value is set by JQuery code, and I've already tested that and it seems to be working perfectly.
What I want is to use courseId as the #PathVariable, and have it work in the following controller method:
#RequestMapping (value="/{courseId}", method=RequestMethod.GET)
public String editCourse(Model model,
#PathVariable ("courseId") String courseId){
System.out.println("CourseID: " + courseId);
return "course-form";
}
Obviously that method is still in the early stages, just trying to get confirmation that it works.
So, what do I have to do to make this happen? Again, I want to pass the value of courseId in the URL, as a RESTful style URL command, using it as a #PathVariable. How do I do this?
Thanks so much.
You can get a very clear explanation here
#RequestMapping (path="/{courseId}", method=RequestMethod.GET)
public String editCourse(Model model,
#PathVariable String courseId){
System.out.println("CourseID: " + courseId);
return "course-form";
}
I am developing a LinkedIn login hook following this example but I got stuck at passing parameters from my .jsp file to the .java class implementing AutoLogin.
If I write a portlet, the values are sent correctly to a processAction method, however here the same approach is not working.
In my linkedin.jsp file i have the following (simplified) structure.
<%
PortletURL linkedInRegiserURL = renderResponse.createActionURL();
linkedInRegiserURL.setParameter(ActionRequest.ACTION_NAME, "linkedInRegister");
%>
<form id="linkedInForm" action="<%= linkedInRegiserURL.toString() %>" method="post"
name='<portlet:namespace/>linkedInForm'>
<input type="hidden" name='<portlet:namespace/>email' id="email" />
</form>
And then inside a javascript method, based on the LinkedIn API, I populate my input and then submit the form.
document.getElementById('email').value = member.emailAddress;
document.getElementById('linkedInForm').submit();
Everything is fine here. The problems start inside the login() function in my LoginHook implements AutoLogin class. If I do a print test, the following results are shown:
#Override
public String[] login(HttpServletRequest request,
HttpServletResponse response) throws AutoLoginException {
String email1 = ParamUtil.getString(request, "email");
String email2 = request.getParameter("email");
String email3 = request.getAttribute("email").toString();
System.out.println("email1 : " + email1); //empty value
System.out.println("email2 : " + email2); //null
System.out.println("email3 : " + email3); //null
//etc.
}
I guess that the problems start here <form id="linkedInForm" action="<%= linkedInRegiserURL.toString() %>", but I am not sure and I don't know how should I pass my email parameter.
PS: I am working with Liferay 5.2.3, so writing a class extending BaseStrutsPortletAction is out of the question.
Params Inside login hooks in Liferay are a bit tricky, you can try 2 things:
Use the following function to retrive the "real" request wich may contains your parameter (Although I´´m not really sure if it´s available in liferay 5.2.3, in Liferay 6 its works):
PortalUtil.getOriginalServletRequest((javax.servlet.http.HttpServletRequest request)
Try with a GET call , instead a POST.
Another way to do it is to save the email as a cookie( in javascript) and then recover it in the autologin hook.
Hope it do some help...
I need to pull all teh messages from a table and display on the jsp page. I have the code like below:
I have the list of messages stored as :
SimpleStringVO string value: Welcome to the XYZ Tool homepage. ,SimpleStringVO string value: Here you can enter your account number ,SimpleStringVO string value: ,SimpleStringVO string value: thank you
When I tried to display this in jsp page, the message is not formated as it is stored. "thank you" comes immediately after the 2nd string. I need to display the space string and then the "thank you" string. (3rd string has just spaces) My code in Jsp is like this :
<td><logic:iterate name="AllNewsCashe" id="news" type="com.fw.valueobject.SimpleStringVO">
<bean:write name="news" property="stringValue"/>
</logic:iterate>
</td>
how to display thise messages as it is without formating ?
If you need to force a space in HTML, you will need to store it as instead of " ". However, since are you using bean:write tag, you can probably use filter property to retain " ":-
<bean:write name="news" property="stringValue" filter="false" />
Here's the description of filter from Struts documentation:-
If this attribute is set to true, the
rendered property value will be
filtered for characters that are
sensitive in HTML, and any such
characters will be replaced by their
entity equivalents.
I am having a web form(JSP) which submits the data to different application, hosted on different server. After submitting the form data, that application redirect back to same JSP page. Now, I want to save the entered the data. What are the different approaches to retain the submitted data in web form. I would not prefer to store the data in DB or any file.
PS: I would like to retain the submitted form data when request again redirected to same JSP page. Therefore, user need not to re-enter the data. Like, data can be stored in Session or Request etc.
Best what you can do is to submit to your own servlet which in turn fires another request to the external webapplication in the background with little help of java.net.URLConnection. Finally just post back to the result page within the same request, so that you can just access request parameters by EL. There's an implicit EL variable ${param} which gives you access to the request parameters like a Map wherein the parameter name is the key.
So with the following form
<form action="myservlet" method="post">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="submit">
</form>
and roughly the following servlet method
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String url = "http://external.com/someapp";
String charset = "UTF-8";
String query = String.format("foo=%s&bar=%s", URLEncoder.encode(foo, charset), URLEncoder.encode(bar, charset));
URLConnection connection = new URL(url).openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("accept-charset", charset);
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset)) {
writer.write(query);
}
InputStream result = connection.getInputStream();
// Do something with result here? Check if it returned OK response?
// Now forward to the JSP.
request.getRequestDispatcher("result.jsp").forward(request, response);
}
you should be able to access the input in result.jsp as follows
<p>Foo: <c:out value="${param.foo}" /></p>
<p>Bar: <c:out value="${param.bar}" /></p>
Simple as that. No need for jsp:useBean and/or nasty scriptlets.
In JSP this kind of thing is usually handled by using a javabean to store the form values and then using the jsp:useBean tag. For example you would create the following javabean:
package com.mycompany;
public class FormBean {
private String var1;
private String var2;
public void setVar1(String var) { this.var1 = var; }
public String getVar1() { return this.var1; }
public void setVar2(String var) { this.var2 = var; }
public String getVar2() { return this.var2; }
}
In your form jsp you'd use the useBean tag and your form fields values would get their values from the bean:
<jsp:useBean id="formBean" class="com.mycompany.FormBean" scope="session"/>
...
...
<input type="text" name="var1" value="<%=formBean.getVar1()%>" />
In your jsp the form data is posted to (then redirects back) you'd have the following code that would push the posted form data into the bean.
<jsp:useBean id="formBean" class="com.mycompany.FormBean" scope="session"/>
<jsp:setProperty name="formBean" property="*"/>
Another option is to just stuff the form data into the session in your save page:
String var1 = request.getParameter("var1");
String var2 = request.getParameter("var2");
session.setAttribute("var1", val1);
session.setAttribute("var2", val2);
...
and reference it in your form (null checking omitted):
<input type="text" name="var1" value="<%= session.getAttribute("var1") %>" />
If I understand the problem correctly (big "if" there), you have a FORM that has a method of POST and an ACTION that is pointed directly to a remote server. When the user clicks "Submit" the browser isn't involving your host in that transaction, the data is going to the "ACTION" recipient. That would make your options limited to implementing a call back relationship with the remote service (possibly beyond your control), setting up a local proxy servlet to intercept the data and forward the POST along to it's intended recipient (which would make the POST originate from the server and not the client (this could likely cause problems)), or utilize some AJAX design pattern to send the form data to two places instead of just one which the FORM tag dictates.
Beyond that, you would need to have some form of local persistence like a database or a file.
Did I help at all?
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.