When I access simple model data like the username using : ${username} everything seems to be fine. But when I try to use ${userdata.uname} I get an error like :
Could not find property uname in class com.mydom.datahandling.userdata
userdata is java class I add to the ModelAndView
ModelAndView mav = new ModelAndView("page37");
mav.addObject("sessionID",ID);
mav.addObject("userdata",p37userdata);
What do I need to do differently ? This seems to be happening whenever I try to use something other than a primitive type or String. I obviously need a bit more education. Do I need to serialize p37userdata?
userdata is
public class userdata{
public String uname;
public String otherstuff;
}
The objects you reference from your EL in your JSP should be java beans (or a map). According to wikipedia (the source of all truth) A bean has the following properties:
They are serializable, have a 0-argument constructor, and allow access
to properties using getter and setter methods.
So you should probably add getters and setters to your userdata class.
Related
I am trying to work with Spring-Data-Rest, but I am hanging that Spring is not binding my body object given via Post.
My domain class looks like:
#Entity
#EqualsAndHashCode
#ToString
public class Rendite{
#Id #GeneratedValue Long id;
double jahresNettoMiete;
public Rendite(){}
}
#RepositoryRestResource(collectionResourceRel = "renditen", path = "renditen")
public interface RenditeRepositoryextends CrudRepository<Rendite, Long> {}
Calling the via Get works fine:
Calling the POST to save an entity calls the Application, too, but it doesnt bind the value to the property:
You appear to be missing getters (and optionally) setters on your entity.
Adding a public getter for the relevant field(s) should allow for both serlialization and deserialization.
See further on this here:
http://www.baeldung.com/jackson-field-serializable-deserializable-or-not
Unintuitively, the getter also makes the private field deserializable
as well – because once it has a getter, the field is considered a
property.
You can control serialization/deserialization in various ways as outlined in the article.
Another approach rather than adding getters would be to use:
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
as outlined in example 4.5 at the below:
http://www.baeldung.com/jackson-annotations
I would like to add attributes to my controller methods which can be inspected using reflection.
I can see how to do this by writing a filter, and I will write an empty filter if that's the only way to achieve what I want, but all I really want is a reflection-visible attribute that can be used to generate documentation. Example:
[OperatorFriendlyDescription("Begin a new message from a letter template and set initial properties.")]
public ActionResult Create(string editorName, int mastKey, ...)
Is there a way to get my OperatorFriendlyDescription attribute without writing a new filter?
(Alternatively, is there some other approach or documentation feature that would allow me to set an operator friendly name for individual controller methods and retrieve this with reflection?)
There is no magical way you can use an OperatorFriendlyDescription attribute without defining it, but if it doesn't need Filter functionality, don't inherit from FilterAttribute.
If you look at the declaration of the MVC FilterAttribute, you will see it is just a specialized System.Attribute.
public abstract class FilterAttribute : Attribute, IMvcFilter
From the MSDN documentation we can verify System.Attribute is the base for all attributes.
Since you have no special functionality needed, inherit from that instead.
An example Attribute in C#
public class ArbitraryAttribute: Attribute
{
public string ArbitraryData { get; private set; }
public ArbitraryAttribute(string arbitraryData)
{
ArbitraryData = arbitraryData;
}
}
Yes. Any attribute that allows being placed on that type of method/class/property, etc., can be used. This class has to inherit from System.Attribute or another class that inherits from that.
VB example, should be very similar in C#. This one can only be placed on methods due to the attribute target attribute. leave off the AttributeUsage attribute for the attribute to be used anywhere.
<AttributeUsage(AttributeTargets.Method)>
Public Class OperatorFriendlyDescription
Inherits System.Attribute
Public Property Description As String
Public Sub New(description As String)
Me.Description = description
End Sub
End Class
I'm just starting with Grails (coming from Rails) and I noticed that Grails really doesn't seem to like scope modifiers on fields in domain classes.
I had understood that all unscoped fields in a domain class were by default public, but if you actually declare it public, Grails won't validate it.
class Person {
public String firstName
public String middleName
public String lastName
}
If you add a constraint, Grails will throw a NotReadablePropertyException exception when you call validate()
class Person {
public String firstName
public String middleName
public String lastName
static constraints = {
middleName nullable: true
}
}
However if you take out the public declaration, everything works normally.
Can someone explain what's going on behind the scenes with the scoping in domain classes? Hard to understand why explicitly declaring something public which is already public would break the framework. I'm guessing you wouldn't want to declare anything 'private' either, although it would be nice if there was away that a fields which shouldn't be manipulated directly could be hidden from consumers of the domain class.
When you add a field to a Groovy class without a scope modifier, it's more that it's inferred to be public than being actually public. The compiler converts the field to a private field and generates a public getter and a setter for it, although it won't overwrite a getter or setter that you wrote. This is convenient because you can later write getters and/or setters to implement business logic and not affect the callers.
But a public field (declared as 'public') is just that - a public field. There's no generated getter or setter. I recommend using a decompiler to see this in action - create a simple POGO in src/groovy, e.g.
class Thing {
String realProperty
public String fieldButNotProperty
}
and open up the .class file with http://jd.benow.ca/ or another decompiler.
GORM automatically assumes that typed properties are persistent unless you exclude some with the transients list. The type is required so it knows how to persist the data, and properties like def name will be ignored. Properties in this sense are similar to JavaBean properties - a matched getter/setter pair.
Hibernate has no support for Groovy and doesn't know what's going on under the hood - it just calls your getters and setters to set and access field data during persistence. So the Groovy compiler adding those in makes it easy for POGOs in Grails to be persisted by Hibernate. And you could do this yourself - add in a getter and setter with correct names and data type (e.g. String getName() and void setName(String name) and it will be treated as a persistent property, even if you do nothing with the values.
The reason for the NotReadablePropertyException is that there's no getter to call for your 'property'. Even though your fields are perfectly accessible, you've effectively hidden them from GORM and Hibernate.
If you add a constraint, Grails will throw a NotReadablePropertyException exception when you call validate()
Never noticed this before, sounds like a bug
it would be nice if there was away that a fields which shouldn't be manipulated directly could be hidden from consumers of the domain class.
If you want to prevent direct access to a property, simply add a getter and setter. In the (contrived) example below, I ensure that name is always read/written as an upper case string.
class Person {
public String firstName
public String middleName
public String lastName
public void setFirstName(String name) {
this.firstName = name.toUpperCase()
}
public String getFirstName() {
return this.firstName.toUpperCase()
}
}
As far as I know, there are many ways to get attributes in other backing beans.
First is:
otherBean = (OtherBean) FacesContext.getCurrentInstance()
.getELContext()
.getELResolver()
.getValue(FacesContext
.getCurrentInstance()
.getELContext(), null, "OtherBean");
String str=otherBean.someString;
And the second is to use session map:
(Set parameters to session map in other Bean)
FacesContext.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.put("someString",someString);
(And get the parameters in the current Bean)
String str= (String) FacesContext.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.get("someString");
And the last is to use Annotation
#ManagedProperty("#{otherBean}")
private OtherBean otherBean;
String str=otherBean.someString;
So which one should I use? What's the differences between those methods? Or is the methods mentioned above wired?
I would use always the last one because it is simply the most convenient. I would use FacesContext only if you can't inject the property or the bean using annotations. FacesContext is a singleton. Unit testing code using FacesContext is a pain.
I've never seen the first method (using the EL resolver) been used outside framework code.
I want to use ManagedBean in my Converter. The ManagedBean is responsible for getting data from database. In Converter I want to convert string into object which must be get from database.
This is my Converter
#FacesConverter(forClass=Gallery.class, value="galleryConverter")
public class GalleryConverter implements Converter {
// of course this one is null
#ManagedProperty(value="#{galleryContainer}")
private GalleryContainer galleryContainer;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String galleryId) {
return galleryContainer.findGallery(galleryId);
...
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object gallery) {
...
}
}
I know that galleryContainer will be null and if I want to inject ManagedBean into Converter I can mark it as ManagedBean too. The problem is that I want to do it in beautiful way, I don't want to look for some 'strange solution'. Maybe the problem is in my application? Maybe there is some other good solution to create object which must get data from database and used in converter? I want also to mention that I will prefer to use DependencyInjection instead of creating new object using new statement (it is easier to test and maintain). Any suggestions?
Instead of using #FacesConverter you should use #ManagedBean, because currently faces converter isn't a valid injection target. Nonetheless, you can choose your converter to be a managed bean, thus refer to it in your view as converter="#{yourConverter}" (by managed bean name) instead of converter="yourConverter" (by converter id).
Basic usage example:
#ManagedBean
#RequestScoped
public class YourConverter implements Converter {
#ManagedProperty...
...
//implementation of converter methods
}
Of course, reading BalusC's invaluable Communication in JSF 2.0 will shed some light on this question as well.
It is also worth mentioning that the scope of your converter bean may be changed to, for example, application or session, if it is not supposed to hold any state.