creating and access properties file in spring mvc - spring-mvc

read this article on SO, and had some clarifying questions.
I put my config.properties under src/main/resources
In spring-servlet.xml config file
I added the following:
<context:property-placeholder location="classpath:config.properties"/>
In my business layer, I am trying to access it via
#Value("${upload.file.path}")
private String uploadFilePath;
Eclipse shows error:
The attribute value is undefined for the annotation type Value
Can i not access the property in the business layer or are property files only read in the controller?
UPDATE::
src/main/java/com.companyname.controllers/homecontroller.java
public String home(Locale locale, Model model) {
MyServiceObject myObj = new MyServiceObject();
System.out.println("Property from my service object: = " + myObj.PropertyValue());
if(myObj.PerformService())
{
///
}
}
src/main/java/com.companyname.services/MyService.java
public class MyServiceObject {
#Value("${db.server.ip}")
private String _dbServerIP;
public String PropertyValue() {
return _dbServerIPaseURL;
}
}
Another site where I found the explanation

Please check that you import Value from org.springframework.beans.factory.annotation package:
import org.springframework.beans.factory.annotation.Value;
also the property placeholder must be declared in the respective context configuration file, in case of controller it's likely Spring dispatcher servlet configuration file.
update You are confusing property-placeholder that post processes bean values, that contain dollar symbol ${<property name>} with Spring expression language container extension that process values containing a hash symbol #{<Spring expression language expression>}, in the link you have shown the latter approach is used.
regarding the instantiation of MyServiceObject myObj
If you want the object to be managed by Spring you should delegate its creation to the container:
if MyServiceObject is a stateless service then it's a singleton with the singleton bean scope, you should register it in your application context, for example with the following xml configuration:
<bean class="my.package.MyServiceObject"/>
and inject it to your controller:
private MyServiceObject myServiceObject;
#Autowired
public void setMyServiceObject(MyServiceObject myServiceObject){
this.myServiceObject = myServiceObject;
}
if many instances of MyServiceObject are required, you can declare it as a bean with some other (non-singleton) bean scope (prototype, or request, for example).
However, as there's only one instance of the controller, you can't merely let the Spring container to autowire MyServiceObject instance to the controller field, because there will be only one field and many instances of MyServiceObject class. You can read about the different approaches(for the different bean scopes) for resolving this issue in the respective section of the documentation.

Here is a method that allows us to fetch whatever values are needed from a property file. This can be in Java code (Controller class) or in a JSP.
Create a property file WEB-INF/classes/messageSource.properties It will be in the classpath and accessible in both controllers and JSTL.
Like any property file, this one consists of a key and a value
For example:
hello=Hello JSTL, Hello Contoller
For the Controllers
Locate the xml file that you use to define your Spring beans. In my case it is named servlet-context.xml. You may need to determine that by looking in your web.xml in cases where you are using the servlet contextConfigLocation property.
Add a new Spring bean definition with the id="messageSource". This bean will be loaded at runtime by Spring with the property file key value pairs. Create the bean with the following properties:
bean id="messageSource"
class = org.springframework.context.support.ReloadableResourceBundleMessageSource
property name="basename" value="WEB-INF/classes/messageSource
In the bean definition file for the controller class (testController) add the messageSource as a property. This will inject the messageSource bean into the controller.
bean id="testController" class="com.app.springhr.TestController"
beans:property name="messageSource" ref="messageSource"
In the controller JAVA class, add the messageSource Spring Bean field and its getters and setters. Note the field type is ReloadableResourceBundleMessageSource.
private org.springframework.context.support.ReloadableResourceBundleMessageSource messageSource;
public org.springframework.context.support.ReloadableResourceBundleMessageSource getMessageSource() {
return messageSource;
}
public void setMessageSource(
org.springframework.context.support.ReloadableResourceBundleMessageSource messageSource) {
this.messageSource = messageSource;
}
In your controller code, you can now fetch any known property value from the bundle.
String propValue = getMessageSource().getMessage("hello", objArray, null);
Using JSTL
Since the property file messageSource.properties is in the classpath, JSTL will be able to find it and fetch the value for the given key.
Add the import of the fmt taglib
taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"
Use the fmt:tag in the JSP to fetch a value from the property file.
Sorry about the pseudo syntax, this editor doesn't seem to render any XML.
fmt:bundle basename="messageSource"
fmt:message key="hello"
Hope this helps others

Related

Failed to start quarkus: java.lang.ArrayIndexOutOfBoundsException: 1

Quarkus application (0.19.1), created from QuarkEE artifact fails to start with:
[io.qua.dev.DevModeMain] Failed to start quarkus: java.lang.ExceptionInInitializerError ..
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at io.quarkus.hibernate.validator.runtime.HibernateValidatorRecorder
EDIT
I've opened a ticket for it:
https://github.com/quarkusio/quarkus/issues/3284
Root cause was a bean validation constraint javax.validation.constraints.NotNull on the static factory method of the enum class. Simplified example:
public enum Gender {
MALE,
FEMALE;
public static Gender fromCode(#NotNull String code) {
return Gender.valueOf(code);
}
}
and having this dependency in your pom:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
Confusing thing is that static factory methods on simple POJO class works.
Note
I'm aware that validation of static methods is not supported by the Bean Validation specification. It is just a hint for IDE.
Java EE 8 Validating Constructors and Methods: Bean Validation constraints may be placed on the parameters of nonstatic methods and constructors and on the return values of nonstatic methods. Static methods and constructors will not be validated.

StrictHttpFirewall in spring security 4.2 vs spring MVC #MatrixVariable

Having upgraded to spring security 4.2.4 I discovered that StrictHttpFirewall is now the default.
Unfortunately it doesn't play well with spring MVC #MatrixVariable since ";" are not allowed anymore.
How to get around that?
Example:
#GetMapping(path = "/{param}")
public void example(#PathVariable String param,
#MatrixVariable Map<String, String> matrix) {
//...
}
This could be called like this:
mockMvc.perform(get("/someparam;key=value"))
And the matrix map would be populated.
Now spring security blocks it.
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";"
at org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:140)
I could use a custom HttpFirewall that would allow semicolons.
Is there a way to use #MatrixVariable without using forbidden characters?
BTW: the javadoc is incorrect https://docs.spring.io/autorepo/docs/spring-security/4.2.x/apidocs/index.html?org/springframework/security/web/firewall/StrictHttpFirewall.html
Since:
5.0.1
I guess it was backported?
You can dilute the default spring security firewall using your custom defined instance of StrictHttpFirewall (at your own risk)
#Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
firewall.setAllowSemicolon(true);
return firewall;
}
And then use this custom firewall bean in WebSecurity (Spring boot does not need this change)
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
// #formatter:off
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
...
}
That shall work with Spring Security 4.2.4+, but of-course that brings some risks!
As mentioned by Крис in a comment if you prefer to use a XML approach, you can add the following part to your securityContext.xml (or whatever your spring-security related xml-config is called):
<bean id="allowSemicolonHttpFirewall"
class="org.springframework.security.web.firewall.StrictHttpFirewall">
<property name="allowSemicolon" value="true"/>
</bean>
<security:http-firewall ref="allowSemicolonHttpFirewall"/>
The <bean> part defines a new StrictHttpFirewall bean with the id allowSemicolonHttpFirewall which is then set as default http-firewall in the <security> tag by referencing the id.
I used combination of following two
https://stackoverflow.com/a/48636757/6780127
https://stackoverflow.com/a/30539991/6780127
First one resolved the
The request was rejected because the URL contained a potentially malicious String ";"
Second one Resolved the
Spring MVC Missing matrix variable
As I am using Spring Security with Spring Web I had to do both And the issue is now Resolved.
I found using #MatrixVariable Following Pattern is useful. First in Url {num} has to be mentioned to use it as #MatrixVariable
#RequestMapping(method = RequestMethod.GET,value = "/test{num}")
#ResponseBody
public ResponseEntity<String> getDetail(#MatrixVariable String num){
return new ResponseEntity<>("test"+num, HttpStatus.OK);
}

Spring Data Rest: Entity serialization with LAZY object cause JsonMappingException

I'm getting the following Exception with a Spring Data Rest project:
com.fasterxml.jackson.databind.JsonMappingException:
No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
(through reference chain: org.springframework.data.rest.webmvc.json.["content"]->test.spring.data.rest.xml.entities.Author_$$_jvstb93_1["handler"])
Certainly, I have some entities that have the fetch configuration = FetchType.LAZY.
I followed many instructions and links, but I still have this exception.
What I have already tried to do (with NO effetcs):
add #EnableHypermediaSupport(type = HypermediaType.HAL) in a config class that extends RepositoryRestMvcConfiguration
#Override configureJacksonObjectMapper in the same class, with also using Jackson2DatatypeHelper.configureObjectMapper():
#Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Jackson2DatatypeHelper.configureObjectMapper(objectMapper);
}
add a "org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter" filter in the web.xml
create a custom class that extends ObjectMapper, with this constructor:
public HibernateAwareObjectMapper() {
Hibernate5Module hm = new Hibernate5Module();
registerModule(hm);
}
and this config:
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="test.spring.data.rest.xml.config.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
No one of the actions above has solved the problem!
How to (definitely) solve this problem?
Thanks.
I have found the solution to this annoying problem.
For every repository of the Spring Data Rest application it has to be defined a custom #Projection; in the projection there will be the necessaries fields.
Pay attention that if there are cycylc references between two entities, the corrispective methods of the projections have to be annotated with #JsonBackReference annotation (for #ManyToOne annotated fields) and with #JsonManagedReference annotation (for #OneToMany annotated fields), otherwise there will be a JSON loop in the JSON serialization.
In every #Repository annotation (or #RepositoryRestResource annotation) it has to be marked the excerptProjection property, with the custom projection.
With this management, there is no need of any other configuration, and the exception for Lazy objects finally is vanished.

TomEE 1.5.2 #Path annotation at interface level still not working

Despite what is claimed here:
for applications not working because of missing #Path at class level
-> it should work now
I still have to annotate my endpoint implementations, as annotations on interfaces are not being picked up.
Is it related to the way I configure JAX-RS, or is it a bug still present in TomEE?
interface:
#Path("myPath") public interface MyEndpoint {
#Path("{id}") String getById(#PathParam("id") long id);
}
implementation:
#Stateless class EJBBackedMyEndpoint implements MyEndpoint {
String getById(long id) { return "foo"; }
}
openejb-jar.xml
<openejb-jar xmlns="http://www.openejb.org/openejb-jar/1.1">
<ejb-deployment ejb-name="EJBBackedMyEndpoint">
<properties>cxf.jaxrs.providers = exceptionMapper</properties>
</ejb-deployment>
</openejb-jar>
resources.xml
<resources>
<Service id="exceptionMapper" class-name="package.MyExceptionMapper"/>
</resources>
beans.xml present with just empty root element
Update:
JAX-RS Spec apparently doesn't mention class-level annotations at all
#Consumes and #Produces work when applied on the interface,
#Path (class level) doesn't work when applied on the interface,
#Path on method level is honoured when routing requests, however the UriBuilder is failing:
UriBuilder.path(EJBBackedMyEndpoint.class, "getById") throws IllegalArgumentException: No Path annotation for 'retrieve' method.
That blog post is perhaps misleading. Putting #Path, #GET, #PathParam or other JAX-RS annotations on an interface is not supported by JAX-RS. Per spec all these need to be on the "Resource Class", which is the #Stateless bean class in this situation.
If you move #Path from the interface to bean class it should work. At least it should get further.

Run-Time Configuring a Hibernate Validation Annotation

I have some business validation logic of the form "X is valid IFF Service Y returns Z", where X and Z are known at compile time, and Y's location is loaded from a Spring configuration file.
I'd like to use JSR-303 annotation-based validation, together with the Spring config, so I can write code like the following:
Custom class level constraint annotation:
#MyValidation
public class X { .... }
ConstraintValidator for #MyValidation:
public class MyValidationValidator implements ConstraintValidator<MyValidation, X> {
private MyService service;
public MyService getService() { return service; }
public void setService(MyService serv) { this.service = serv; }
//Validation Logic...
}
Spring config:
<bean id="ServiceY" class="...">
...
</bean>
<bean id="mvv" class="MyValidationValidator">
<property name="service" value="ServiceY" />
</bean>
But my attempts at combining these in that fashion are failing, as the validator's property is not getting set.
Right now, I'm using Spring AOP Interceptors as a workaround, but that's not ideal in my mind.
One of the other questions here, made me think of using a properties file/property, but wouldn't that require me to repeat the service's configuration?
Another mentioned defining the constraint mapping programmatically, but if I'm doing that, I'm probably better-off with my workaround.
Any clues on how to do that dynamic configuration?
You should use Spring's LocalValidatorFactoryBean to set up a Bean Validation validator:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
A validator set up that way will internally use a ConstraintValidatorFactoryimplementation that performs dependency injection on the created validator instances, just mark the service field in your validator with #Inject or #Autowired. Note that it's not required to set up the constraint validator itself as Spring bean.
You can find more details in the Spring reference guide.

Resources