I have a bean like this:
public class QuestionBean
{
private int myQuestionId;
private String myContext;
private String myQuestionType;
private String myQuestionAns;
// setters and getters here
}
Which I put in a list List<UserBean> = new ArrayList<UserBean>;
I want to use this list with the form, consider something like this:
<form:form commandName="questionBean"..
<form:input path="myQuestionId"...
My case is this:
Each question will have the attributes I listed in the bean ( that is why I put the bean in a List )
There is only 1 Form
My question is how can I use the List of bean, if the form is only one and I need the a List of bean to be binded to each question?
Related
I have following bean file.and I would like to put this bean to Map<String, Object> as key of bean.
Bean.java
#SuppressWarnings("serial")
public class bean implements Serializable {
#Getter #Setter
private param
}
BaseAction.java
public class BaseAction extends ActionSupport implements SessionAware {
// session
#Getter #Setter
protected Map<String, Object> session;
public execute(){
session.put("loginUser", "userA");
session.put("bean", bean);
session.get("bean");
}
}
After execute above setter,I retrieve this Bean by following getter.
It seems that session.get("bean") seems to be regarded as Object. and caught some error , so that we cannot use bean's setter and getter.
#Getter #Setter
private Bean bean= new Bean();
setBean(session.get("bean"))
method setBean(Bean) is not applicable for the arguments(Object)
Are there any good way to put bean to Map<String, Object> ?
The session Map is implemented as Map<String, Object>, and you need to keep types at least to the setter method of the SessionAware interface.
You can convert any object you put into the session to different types using Struts Type Conversion. Since you injected a session object from the action context, it gets and puts objects to the #session via OGNL on the view layer. It uses property accessors of the objects to get its values. You still keep the value as Object in the Struts tags attributes.
If you know the instance type of the object you put into the session then you can always convert to string values to this type from parameters of the request. No need to explicitly typecast to the instance type.
The following code will work the same as above.
#Getter #Setter
private Object bean= new Bean();
setBean(session.get("bean"))
You can try to convert type of session.get("bean") to Bean just like this:
setBean((Bean)session.get("bean"))
So my problem is, I have a bean which I would like to inject dynamically based on runtime values. Lets say I have class A which has private variable B. I would like to inject my variable B (upon creation of the bean) via spring with value I got from user (for example). How can I do that ? Should I just use getBean() and then use setter method for my variable or is there any better way ?
EDIT:
#Bean
class A {
private int B;
...
}
main {
context = someContext("myConfigFileWhereBeansAreDefined");
int value = getIntFromUser();
// I want to have myNewBean injected with "value" i got from user
A myNewBean = context.getBean("A");
}
I have a Spring managed bean...
#Component("Foobean")
#Scope("prototype")
public class foobean {
private String bar1;
private String bar2;
public String getBar1() {
return bar1;
}
public void setBar1(String bar1) {
this.bar1 = bar1;
}
public String getBar2() {
return bar2;
}
public void setBar2(String bar2) {
this.bar2 = bar2;
}
}
...and because I am using Dojo Dgrid to display an ArrayList of this bean, I am returning it into the controller as a JSON string:
#Controller
#RequestMapping("/bo")
public class FooController {
#Autowired
private FooService fooService
#RequestMapping("action=getListOfFoos*")
#ResponseBody
public String clickDisplayFoos(
Map<String, Object> model) {
List<Foobean> foobeans = fooService.getFoobeans();
ObjectMapper objMapper = new ObjectMapper();
String FooJson = null;
try {
FooJson = objMapper.writeValueAsString(foobeans);
} catch (JsonGenerationException e) {
etc.
}
However, my grid needs an additional column which will contain a valid action for each Foo; that action is not really dependent on any data in individual Foos -- they'll all have the same valid action -- repeated on each line of the resulting DGrid -- but that value is actually dependent upon security roles on the session...which can't be sent to the front end in a Json. So, my solution is twofold:
First I need to add a "virtual" Json property to the bean... which I can do in the bean with #JsonProperty on a method...
#JsonProperty("validActions")
public String writeValidActions {
return "placeHolderForSerializerToChange";
}
...but it just generates a placeholder. To really generate a valid value,
I need to reference the security role of the session,
which I am very reluctant to code in the above method. (A service call in
the domain bean itself? Seems very wrong.) I
think I should create a custom serializer and put the logic -- and the reference
to the Session.Security role in there. Are my instincts right, not to
inject session info into a domain bean method? And if so, what would such a
custom serializer look like?
Yes, I wouldn't put Session Info in to the domain or access session directly in my domain.
Unless there is a specific reason, you could simply add the logic in your action class.
public String clickDisplayFoos(){
List<Foo> foos = service.getFoos();
for(iterate through foos){
foo.setValidAction(session.hasSecurityRole())
}
String json = objMapper.writeValueAsString(foobeans);
return json;
}
I don't like the idea of setting new values as part of the serialization process. I feel custom serializers are meant to transform the representation of a particular property rather than add new values to a property.
my project is using Spring data mongodb. I was not having below error until i made an edit to one of the document that has a field with Array of Documents in it. It was working fine before but now I keep getting the below error.
The field i updated was impapps in the Projects POJO class. I am not sure how to clear this error tried different things but did not work out.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/mongodproject] threw exception [Request processing failed; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface] with root cause
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:101)
at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:60)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:232)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:212)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1008)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$100(MappingMongoConverter.java:75)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:957)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getValueInternal(MappingMongoConverter.java:713)
Here are my POJO and Spring Repository class.
Project POJO Class
#Document(collection="releases")
public class Project {
#Id
private String id;
......
#Field("impapps")
private List<ImpactedApplications> impapps=new ArrayList<ImpactedApplications>();
.....getters/setters
}
ImpactedApplication POJO Class:
public class ImpactedApplications {
#Field("appid")
private String appId;
.....
#Field("repository")
private List<ScriptsRepo> rep=new ArrayList<ScriptsRepo>();
#Field("artifacts")
private List<Artifacts> artifacts=new ArrayList<Artifacts>();
//getter and setters
}
Artifacts POJO Class
public class Artifacts {
#Field("artifacttype")
private String artifactType;
#Field("documentlink")
private String documentLink;
#Field("arttestphase")
private String artTestPhase;
#Field("artifactname")
private ArtifactsEnums artifactsNames;
#Field("startdate")
private String startDate;
#Field("enddate")
private String endDate;
#Field("peerrev")
private boolean peerReview;
#Field("busrev")
private boolean busReview;
#Field("na")
private boolean na;
Spring Repository classes
public interface ProjectRepository extends Repository<Project, String> {
Project findById(String id);
List<Project> findByYearAndReleaseMonthNoOrderByProjectNameDesc(String year,String month, Sort sort);
Project findByYearAndReleaseMonthNoAndId(String year, String month,String id);
Whenever i call the above methods i keep getting the exception.
Below is how my document is looking currently.
The impapps field in your document is not an array but a nested document. So if you change your List<ImpactedApplications> to a simple ImpactedApplications this should read fine.
I have got the same exception :
Try to declare your field like this :
#Field("impapps")
ArrayList<ImpactedApplications> impapps = new ArrayList<ImpactedApplications>();
I don't like to do that but it works for me.
edit:
My issue was due to unwind operation during aggregation.
It transform array (declared as List<> in my class) into object
and then reflection doesn't work because spring was expecting a list.
use ArrayList someObjects instead of List someObjects.
It worked for me.
This question already has an answer here:
JSF does not populate #Named #RequestScoped bean with submitted input values
(1 answer)
Closed 5 years ago.
I have a bean with a field called 'name', and a JSF form that has an inputText mapped with this field. The initial value of the field is well displayed on the form.
The problem is when I submit the form, the value is not updated with the content of the inputText. In the savePlayer() method below, the value of name is always 'name', not what I typed inside the form input.
The bean :
#Named
#RequestScoped
public class PlayerForm {
#Inject
private PlayerRepository playerRepository;
private String name = "name";
public String savePlayer(){
Player player = new Player();
player.setName(name);
playerRepository.savePlayer(player);
return "saveUserOk";
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
The form :
<h:form>
<h:inputText value="#{playerForm.name}" />
<h:commandButton value="Submit" action="#{playerForm.savePlayer}" />
</h:form>
Thanks very much for any help!
This can happen if you imported #RequestScoped from the package javax.faces.bean (JSF) instead of from javax.enterprise.context (CDI). Every single EL expression #{} would then create a brand new and completely separate instance of the bean. The given form example would then end up in two instances of the bean, one where the name is set and another where the action is invoked.
The javax.faces.bean.RequestScoped annotation can only be used in conjunction with JSF's own #ManagedBean annotation not with CDI's #Named annotation.