How to use bean in JSP with only <jsp:useBean>, not MVC?
Assume you have a grade.txt file which contains following data:
Tom 90
Jerry 70
Katy 80
John 60
It asks you to create a bean named grade.java, a JSP page named graderesult.jsp, and a html page named gradecheck.html.
gradecheck.html provides a input textbox and a button submit, once you submit the name of the student, the graderesult.jsp will communicates with bean to show the name and the score corresponding to the person.
You can make use of <jsp:setProperty name="beanname" property="*" /> to "automatically" set all request parameters as bean properties matching the property name. As this is a typical homework question, I won't give complete code examples, but only hints:
Create a bean Grade with a property name.
Add a constructor which loads the data from the text file into a Map<String, Integer> property representing name-score pairs. Learn more about Java IO here and about Java Maps here.
Add a "special" getter getScore() which returns the score from the Map using the name as key.
Create a form with <input type="text" name="name"> in the gradecheck.html. Let the form submit to graderesult.jsp. The request method doesn't matter, I would prefer POST though.
In the graderesult.jsp use <jsp:useBean> to declare and instantiate the bean in request scope and use <jsp:setProperty> to "automatically" set all input values in the bean.
Use EL to show the name by ${grade.name} and the associated score by ${grade.score}.
Good luck.
Related
I have trouble to understand how to stop Spring from initializing the child member object of a form bean if none of his fields were modified by the corresponding form. For example I have an User Object that has a field Address, I pass the empty User instance to the form (the Address is null at the time).
In the form I have input fields for all User as well as Address fields:
<form action="#" th:action="#{/user/add}" th:object="${user}" method="post">
...
<input type="text" th:field="*{address.street}"/>
<input type="text" th:field="*{firstName}"/>
...
when I set a breakpoint in the corresponding controller method, the Address object exist within the User object and all its fields are null,0,false(default values). I know the initialization occurs in the WebDataBinder. How can I instruct it not to do so?
The same happens with the dynamic lists, if i had List then the List would get a new entry after form submit.
Would really appreciate any help
You need that object instantiated or you could not store the values entered in the form anywhere.
If you don't want to save the empty object to the DB then you probably need to check it on modification before saving.
I would like to set a value of bean from another bean once a page is displayed. The target dataTable is included because it is also used in another context.
Like I said before, there are two beans involved:
bean1 'gets' a parameter, will load an object and display some properties.
bean2 is the bean that is responsible for the filtering / search in the dataTable.
relevant parts:
<f:metadata>
<f:viewParam name="objectId" value="#{bean1.objectId}" />
</f:metadata>
<!-- resolving works -->
#{bean1.object.name}
included search:
<p:dataTable>...<p:inputText value="#{bean2.value}">...</p:dataTable>
How to assign (a substring of) bean1.object.name to the value of the input text once at page request but keep the existing value attribute of the field? I don't want to mess up the included page but would prefer to solve it "outside" in my including jsf/xhtml file.
The best way to do this is using javascript.
Define a input hidden tag to hold the value of #{bean1.object.name}.
Now in javascript get the value of this field using document.getElementById("").value
Take the substring and assign to input text field using javascript.
I have a <form:form> in my jsp page with several <form:input> fields (so, fields are databound). Some of those fields are populated by user, but some, instead of waiting for user to enter some value, need to pre-populated with the value of parameter sent to this page from another jsp page, through the spring controller. How to write that parametar into <form:input> so user doesn't have to?
If I understand your question correctly, you want to prepopulate some fields with values already submitted previously.
All you need to understand is that with the Spring form taglib, Spring expects you to put a command object in the model and will bind the values in that command object to the form fields.
If you don't specify the key for this command object in the model, the taglib will look for it with the key "command". You can specify a different name though with the commandName attribute on the form tag, such as:
<form:form commandName="myModelObject">
Spring would now look for an object in the model named myModelObject to use to bind the form tags.
The other thing you then need to do is in the form tags in your Spring form, reference the fields in your command object. So, for example, let's say your command object has a field firstName, you'd have an input tag like this:
<form:input path="firstName" />
The path attribute tells the attribute what fields in the command object it should bind with.
So then you simply put the command object in your model with the appropriate fields prepopulated and the corresponding form fields will have those values prepopulated. Such as if you put an object in the model with the name myModelObject that has a field firstName, it will be prepopulated with whatever firstName is currently set to in that object.
I have a HashMap<Long, ClientProperties> that I'm putting on the ServletContext at startup.
//During application-startup:
//getProperties() returns HashMap<Long, ClientProperties>
context.setAttribute("clientProps", clientManager.getProperties());
ClientProperties is a POJO with 5 attributes that i need to access in my jsp.
Basicly I need to get the correct POJO (by HashMap-key) and access its properties in my jsp.
More spesific (for example purposes), one of the POJO attributes is clientLogo
In my jsp i now have:
<img src="<c:url value='/images/logo.png'/>" alt="Logo">
I need to replace the path to the logo-file with the clientLogo-property of the POJO.
The HashMap-key to use should be extracted from the User-object stored in the session. It can be retrieved like this: ${sessionScope['user'].clientId}
Any ideas?
Using struts2 and spring btw if that matters.
To get an attribute foo from the servlet context, you use the same syntax as to get it from the session, but replace sessionScope by applicationScope.
But you have so many nested things here that you should define variables:
<c:set var="map" value="${applicationScope['clientProps']}"/>
<c:set var="mapKey" value="${sessionScope['user'].clientId}"/>
<c:set var="pojo" value="${map[mapKey]}"/>
<c:set var="clientLogo" value="${pojo.clientLogo}"/>
<c:url value="${clientLogo}"/>
Note that this is typically the kind of hard work that you should not have to do in the view. Implement the retrieval of the image path in the controller, in Java, and make it available as a property of your action/form, and access it directly from your view.
I'm trying to understand the concept of data binding in Spring-MVC with Velocity (I'm learning this framework and porting an app to this platform).
I'm used to getting form variables using request.getParameter("username"), in the Spring world it seems that I can perform validation and such against "form objects" e.g. a datamodel style object that represent all the fields of a form.
The concept of a validator makes sense, but marshaling the data from a query string to these objects is fuzzy for me still. This is the concept of "Data Binding" correct?
If I'm correct to this point a few specific questions:
When a "binding" is made between a form variable (say "username" for example) and the the field of an object (say org.a.b.MyNewUserFormObj.username) is that "binding" a permanent definition such that all subsequent http posts of that form cause the username form variable to be assigned to org.a.b.MyNewUserFormObj.username?
How in the world do I accomplish the above binding definition? (if what I've said up to now is correct I feel like Costello in 'Who's on First', I don't even know what I just said!), I just need a conceptual picture.
Thanks for setting straight a brain gone astray.
There is no magic in data binding.
Actually, Spring simply populate properties of #ModelAttribute object with the values of request parameters with the corresponding names (in the simpliest case request parameter have the same name as a property, but nested properties are also supported).
So, if you have
<input type = "text" name = "firstName" />
and
public class Person {
private String firstName;
... getters, setters ...
}
you get a value from the form field.
Spring also provides convenient method for creating HTML forms. So, instead of creating form fields manually, you can write in JSP:
<form:form modelAttribute = "person" ...>
<form:input path = "firstName" />
</form:form>
or in Velocity (note that in this case <form> is created manually and property path is prefixed with the model attribute name):
<form ...>
#springFormInput("person.firstName" "")
</form>
Fields of the forms generated this way will be prepopulated with the values of the corresponding properties of the model attribute (that's why model attribute name is needed).