i got a simple programm that begins on an input form where the user fills in 3 numbers. The form action refers to a controller servlet where i store the data in the Bean class with the setter methods I have defined.
number.setNumber1(Double.parseDouble(request.getParameter("number1")));
Till now I stored the Number object in the request with
request.setAttribute("numbers", number);
and forwarded it to the output page where i could get it with ${numbers.biggestNumber ( getter-Method that simply determines the biggest Number) }. A tutorial i am using says I could also get the data directly from the Bean by using this piece of code:
<jsp:useBean id="num" scope="session" class="model.Numbers"/>
<c:out value="${num.biggestNumber}/>
but somehow the Bean uses another object of the Numbers-class. I see the advantage of this technique, because I dont have to put the Numbers object into the request. Can someone tell me how I can use the same Numbers object I stored the data before?
I already read that I shouldnt use "jsp:setProperty..." to store the data on the input page, but if i cant get the information i wrote manually to the Bean, I have to ask myself why I should use the JSP JavaBeans annotation at all.
I used the search function but could not find an answer suitable to my question, or maybe I am just not experienced enough to get them in a more advanced context... Any help would be welcome
if you are using this one,
request.setAttribute("numbers", number);
And using requestDispacher redirecting then at target page you can do likewise,
into JSP file :
<jsp:useBean id="numbers" scope="request" class="model.Numbers"/>
<c:out value="${numbers.biggestNumber}/>
Here,
you did with wrong scope=session, means you are putting value into 'request' scope and try to pull it from session is wrong.
also maintain name of attribute 'same' while putting/getting from scope. here, name="numbers" maintain while putting/getting
Okay my mistake was that I thought JavaBeans-Jsp-Tags would save time and code. Indeed I had to create a HttpSession-Object that stores the ID of the used JavaBean
HttpSession sess = request.getSession(true);
sess.setAttribute("number", number);
Now the JavaBean-Tag in my Output.jsp knows which object to use (the one created in the Input.jsp). As far as I do understand now, the only advantage of the JavaBean-Jsp-Tag above normal Parameters added to the Request is that I can use the Bean-Class in the whole Session and am not dependend on the Request-Object.
Related
I need to implement a controller that has a command object that is backing a filtering form for a search across multiple entries.
The problem is that the i was asked to do that without using POST request, instead using GET request only, and there before loosing the functionality of the default data binding that springs makes happily for us.
So i tried to implement a method, inside my controller, that looks like this:
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (isSearchRequest(request)) {
MyCommandObject myCommandObject = (MyCommandObject) getCommand(request);
System.out.println(managePositionsForm);
}
return super.handleRequestInternal(request, response);
}
But the getCommand returns me a brand new CommandObject with no values, despite that the values are present in the request object (i could retrieve then using the getParameter method of HttpServletRequest). But there isn't any binding.
So the question :
1) Is there any way to archive this?
2) Also is very important, that all the values in the form, are lost and, eventually (if this problem is solved) i will need to "persist" the filters for the users in order to avoid re entering after the first search.
Auto Response : setSessionForm(true); looks like can do the work! (According to javadoc)
Thanks to all!
Greetings
Victor.
Okey, i found a way to archive what a was looking for.
I will explain for the sake of those have the same problem before, and hoping to find a experienced user to validate this method... some quiet common is there a multiple ways to do a same thing and as human beings is very difficult to know without proper acknowledge the right path.. so this i a found looking inside the AbstractFormController (that is excellently documented with javadoc).
So what i did was the following, on my controller constructor i add these lines at the end :
setSessionForm(true);
setBindOnNewForm(true);
That all the magic!
But is not enought with setSessionForm(true). According to javadoc the setBindOnNewForm(boolean) method does the following :
/**
* Set if request parameters should be bound to the form object
* in case of a non-submitting request, i.e. a new form.
*/
So my guess are that these two flags are necessary to be marked as true, because :
The setSessionForm makes posible to store as a session attribute the form object, so "is stored in the session to keep the form object instance between requests, instead of creating a new one on each request" (according to javadoc of the setSessionForm method).
The setBindOnNewForm allows the population of the form object with the initial request (despites what type of request method we have). According the javadoc found the AbstractFormController "Only if bindOnNewForm is set to true, then ServletRequestDataBinder gets applied to populate the new form object with initial request parameters..."
But still i noticed, following the controller flow with a debugger, that the population is happening inside the method "getErrorsForNewForm(HttpServletRequest request)".. that is where a concrete object of type ServletRequestDataBinder is used IF the setBindOnNewForm is true, and later (as the javadoc stated) the onBindOnNewForm method is invoked, allowing the programmer to overwrite it with custom behavior, the default behavior is just empty (again this was double checked against the code of AbstractFormController).
I have an strong felling to validate my thoughts here, so if anyone can help me, that would be alright, besides the problem is solved!
Thanks to all in advance!
Greetings.
I'm really new to JSTL and having trouble grasping exactly how for each loops work. But say in my java bean I have a very simple while loop, that goes through and grabs properties of an object. I get the expected output from the loop when I log it. Which is simply a string that looks something like headerTest, headerMetaTest. Here is the code from my java bean:
Iterator<Resource> serviceList = null;
serviceList = resource.getChild("header").listChildren();
while(serviceList.hasNext()){
Resource child = serviceList.next();
headerTitle = child.adaptTo(ValueMap.class).get("headerTitle", "");
headerMeta = child.adaptTo(ValueMap.class).get("headerMeta, "");
}
However when I try to access it in the JSTL I'm getting nothing:
<c:forEach var="child" items="${serviceList}">
<p>${child.headerTitle}</p>
<p>${child.headerMeta}</p>
</c:forEach>
The puzzling part is I get no errors, nothing simply returns. Any ideas? Really, really lost on this one and any help is greatly appreciated. I'm a newb to this so code samples are a good way for me to learn and would be great if possible.
There are four scopes to be aware of in JSP pages.
page, request, session and application.
JSTL tags will usually look for attributes in that order.
page maps to attributes assigned during the processing of the page, these are usually quite
rare.
request is for attributes assigned to the ServletRequest, they are the most common
attributes to use as they last for the page request duration, and are then discarded.
eg
public void processMyServlet(ServletRequest request, ServletResponse){
...
request.setAttribute("myAttribute",attributeValue);
...
}
session is for attributes assigned to the HttpSession. This is useful for
user values that are used often during the user session.
eg
public void processMyServlet(HttpServletRequest request, HttpServletResponse){
...
request.getSession().setAttribute("myAttribute",attributeValue);
...
}
application is for attributes assigned to the ServletContext, this is useful for
values that are consistent across the application and do not change.
eg
public void processMyServlet(HttpServletRequest request, HttpServletResponse){
...
request.getServletContext().setAttribute("myAttribute",attributeValue);
...
}
If you are calling a servlet that dispatches your jsp then at the very least you will need.
request.setAttribute("serviceList",myResourceCollection);
somewhere during the servlet processing.
if you are doing everything in jsp then you will need something like
<% java code to create collection
request.setAttribute("serviceList",myResourceCollection);
%>
I have a problem where i am supposed to stop XSS vulnerabilities . A typical example here is in vulnerable.jsp :
<h2><%= myObj.getElf() %></h2>
The myObj is an object of the kObj class , which i have created in the jsp file :
<% kObj myObj = KSession.getPostInfo(session); %>
The problem here is there is no use of use bean here in this framework. As a result usage of core JSTl becomes troubling and it does not work. For e.g when i try to do :
<h2><c:out value={$( myObj.elf)} /></h2>
It does not work and tells me that there is no value for the object elf with the . operator.
The kObj class is not strictly a POJO as well. Can some one suggest what i can do here ?
JSTL tags as demonstrated in your code use EL. Objects used in EL should be in one of the known scopes: request, session, etc. So in your EL expression, you should try using the key with which the instance was actually stored in the session rather than myObj.
You seem to be getting the object from the HTTP Session, not sure what KSession is, but I assume it internally gets it from the session map. Lets assume the actual key by which the object is stored in the session map is "myObjKey". So instead of using "${myobj.elf}" use "${myObjKey.elf}"
Part1:
I am trying to search a way to capture and format user input on an automated way. I have a lot of fields and formatting everything with following method becomes bulky:
<s:param name="value" value="thenumber == null ? '' : getText('{0,number,#,##0.00}',{thenumber})" />
Is there an efficient way to automate this?
Part2:
I want to capture and be able to process invalid user input before it gets passed to the correct setter, in this case setTheNumber(Double theNumber). Preferrably with tags from the page itself. Because inserting '10.00aaab' will throw me an error.
Creating a temporary String field for every number I need to set is an invalid option as I would need to create around ~170 setters for this with exception handling and string parsing.
Short: I want to hook own code between my Http post message and my java class setter.
Previously I used #TypeConversion annotation on the setters and getters but I can't use this anymore as my java class with all values is in another project that can't have dependencies to xwork2 packages.
Thanks in advance,
I have a spring bound form (modelAttribute) which displays the user information.
The user's telephone number is displayed in a formatted manner but a requirement is that the number is saved to the database without any signs.
So in the getter method of my user object I format the telephone number according to the rules and in the setter I put the code to remove the special signs.
The formatting part works fine, but setter part where I remove the signs does not seem to occur.
In my constructor I also did:
setTelephoneNumber(TelephoneNumber);
So the constructor also invokes the setter.
I'm using Spring 3.0.4 and Spring-mvc.
Any input on this issue and how to resolve it would be appreciated.
edit:
controller section:
model.addAttribute("user", user);
JSP (shortened it a bit but this is the gist. submitUrl is due to a portal environment:
<form:form action="${submitUrl}" modelAttribute="user">
<form:input path="telephoneNumber"/>
</form>
Model telephoneNumber setter:
if(!StringUtils.isBlank(telephoneNumber)){
this.telephoneNumber = telephoneNumber.replaceAll("[^0-9]", "");
} else{
this.telephoneNumber= "";
}
And I think so because the value lands in the database with the formatting I used. (spacing)
Even if it is not the correct answer to your question:
I strongly recommend to do the formating in an other way then by setter getter
Spring 3.0 provideds something they called "type conversion"
spring blog with example
spring reference "Validation, Data Binding, and Type Conversion"
Using this would be much more cleaner.
Back to your question:
Spring path binding: is it bound directly to the variable or does it invoke the constructor/setters?
As fare I understand the Java Doc and some code snippets, Spring uses BeanWrapper (BeanWrapperImpl) to set the values of Beans (#see Reference: 5.4 Bean manipulation and the BeanWrapper). And BeanWrapperImpl behaves like the reference said:
uses setter and getter to access "simple" values.
It is exactly like the reference said in section "5.4.1 Setting and getting basic and nested properties": For an expression "name":
Indicates the property name
corresponding to the methods getName()
or isName() and setName(..)
So at least this answer your question, so I assume that the cause for your problem is some thing else.