how to inject userContext in JSP pages - spring-mvc

how do I retrieve the values of a context in a jsp file? this tutorial is perfect for what I need but I need to retrieve the property values in the jsp file.
http://www.mkyong.com/spring/spring-listfactorybean-example/
is there a specific interceptor that I can use?

You're referring to spring context right?
In general, JSPs should be a template of a page only, so the only interaction with the back-end should be accessing the values of the scoped attributes. This means that whichever bean value you need you should instead store in the model.
This being said, there are a few ways you can expose spring beans to view. Depends on which View resolver you're using, the ones that extend UrlBasedViewResolver have the setExposeContextBeansAsAttributes property
Set whether to make all Spring beans in the application context
accessible as request attributes, through lazy checking once an
attribute gets accessed. This will make all such beans accessible in
plain ${...} expressions in a JSP 2.0 page, as well as in JSTL's c:out
value expressions.
Default is "false".
You would configure it like
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="exposeContextBeansAsAttributes" value="true" />
</bean>

Inject your bean (or source) of userContext into your controller, so you have access to it in a local variable.
So taking the example maybe this is:
#Autowired
private CustomerBean customerBean;
#RequestMapping(value="/foobar/index.jsp")
public String (HttpServletRequest request) {
Object userContext = customerBean.getLists();
request.setAttribute("userContext", userContext);
return "/foobar/index.jsp"; // expecting JstlView viewResolver to map to JSP file
}
In the CONTROLLER simply add data to the HttpServletRequest (which you just add as argument to the method to introduce it).
Then use request.setAttribute("userContext", userContext); then in JSP simply access it using Expression Language like ${userContext}. There are other ways using Spring model paradigm but they effectively do the above.
Ensure you have your JstlView setup to https://dzone.com/articles/exploring-spring-controller
More info about how to use EL in JSPs to retrieve data attached to request:
How to obtain request / session / servletcontext attribute in JSP using EL?

Related

Why Spring interceptor is bypassed for bad URLs?

My web application runs on Spring (MVC) 4.2.9.RELEASE, Hibernate 5.1.3.Final, and Spring Data 1.8.2.RELEASE.
I have the following interceptor in the Spring context.
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="1"/>
<property name="interceptors">
<list>
...
<ref local="myIntercepter" />
...
</list>
</property>
</bean>
The interceptor "myIntercepter" is able to intercept valid URLs such as
http://localhost/s?mid=cflbv1zipb8d7&lang=en_US
However, for the following invalid URL (has a question mark in the end)
http://localhost/s?mid=cflbv1zipb8d7&lang=en_US?
The interceptor does not get called. I am not sure why this behavior happens. I have to make sure all web traffic to go through the interceptor.
If you want to make sure a piece of code gets executed for every web request coming in, I'd recommend using a Filter instead of a HandlerInterceptor. Spring MVC might be trying to parse the querystring or something to that effect prior to the interceptor being called, or it can't find a handler due to the invalid url.

How to avoid display jssession id in Url using spring 4 java annotation configuration

I found is that jsessionid is injected in the url, how can i avoid displaying jsessionid in url. I am using cookies for to have store login information I have not used any http session. I found below suggestion in xml configuration how would I write using spring java annotation configuration can anyone just let me know
<property name="securityContextRepository" ref="securityContextRepositoryNoJSession"/>
<bean id="securityContextRepositoryNoJSession" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository">
<property name="disableUrlRewriting" value="true"/>
</bean>

How to use WAS standard persistence provider with Spring

I'm developing a portlet which runs in WebSphere Application Server ( - I accept the same problem to appear if it was a servlet instead of a portlet). At the moment it depends on Hibernate. As WAS provides a JPA implementation itself, which is a modified version of OpenJPA 2.0, I want to get rid of Hibernate.
This is my setup. persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
>
<persistence-unit name="default" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myDb</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect" />
</properties>
</persistence-unit>
</persistence>
myPortlet-portlet.xml
<!-- ... -->
<tx:jta-transaction-manager />
<jee:jndi-lookup jndi-name="jdbc/myDb" cache="true" id="dataSource" expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="default" />
</bean>
In my DAO-classes I access the entityManager by using annotations:
#PersistenceContext(unitName = "default")
private EntityManager entityManager;
Everything works fine using Hibernate.
According to WebSphere Application Server docs, the default persistence provider is used if you don't specify it by using the <provider/>-tag in persistence.xml. But after commenting out the provider specification, Spring throws an exception due not being able to find the provider-class:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in PortletContext resource [/WEB-INF/myPortlet-portlet.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No PersistenceProvider specified in EntityManagerFactory configuration, and chosen PersistenceUnitInfo does not specify a provider class name either
How can I use the provided JPA implementation together with Spring (Portlet) MVC?
Short answer
You cannot use WebSphere's default provider by omitting the provider, if you want to use LocalContainerEntityManagerFactoryBean.
Long answer
Normally an entity manager is created by an entity manager factory provided by the container. You retrieve it by doing a context loopkup (EntityManager em = (EntityManager) ctx.lookup(...)) manually or use Springs jndi-lookup capability:
<beans>
<jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
In the question, a different approach is used, a LocalContainerEntityManagerFactoryBean, which creates an entity manager factory itself. This entity manager factory is a proxy that implements all the interfaces of the native entity manager factory. For creating such a proxy, Spring must know the class of the native entity manager factory. Spring uses three different ways to determine the class:
Detect it by the <provider/>-entry in persistence.xml
Asking a jpaVendorAdapter (specified in the equally named property of the factory bean)
Using the entityManagerFactoryInterface-property of the factory bean
And that's why you cannot completely omit the specification of your provider.
This is most likely happening because the Spring JAR(s) that you include with your application contains a different implementation of the Persistence class, or other JPA classes, used to "bootstrap" JPA.
If you'd like to use WebSphere's default provider (or, more precisely, to use whichever JPA provide configured through WebSphere's administration screens), then you must ensure that the JPA "bootstrapping" code being called during runtime is WebSphere's, not yours.
You should look for a Spring distribution JAR that doesn't mess with JPA.

Custom HttpMessageConverters does not take precedence for String objects in Spring 3.1

My Spring 3.1 project that has a custom HttpMessageConverter specified like this:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="myproject.MyCustomHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
It works, as I can convert return values marked with #ResponseBody to appropriate values. However, when the method's return value is a String object, my custom message converter will not be called (default converters seem to handle it, display the String as response directly).
This can be resolved if I include a register-defaults="false" like this:
<mvc:annotation-driven register-defaults="false">
<mvc:message-converters>
<bean class="myproject.MyCustomHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
This behaviour is not consistent with what is mentioned in this blog post in springsource that says: "The list of message converters provided this way take priority over the message converters the MVC namespace registers by default".
Any idea?

How to enable Spring 3.0 MappingJacksonHttpMessageConverter with #ResponseBody AND pre-Spring-3.0 Controller SimpleUrlHandlerMapping together?

As the title suggests, I'm trying and failing to get the following combination working in Spring 3.0:
pre-Spring-3.0 controllers mapped with SimpleUrlHandlerMapping, and,
a Spring-3.0 #Controller using MappingJacksonHttpMessageConverter and #ResponseBody to return JSON.
All the pieces work - except when put together!
In more detail, I have an existing Spring web-app which includes many pre-Spring-3.0 controllers. These implement Controller and are mapped explicitly with a SimpleUrlHandlerMapping bean. (So one solution is to change them all to #Controller style). The same web-app (DispatcherServlet) also supports several newer controllers annotated with #Controller.
My bean config includes the following, and all is good:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/path/name.ext">mySpring25Controller</prop>
</props>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
Now I'm adding, to a new controller annotated with #Controller and #RequestMapping, use of MappingJacksonHttpMessageConverter so that with #ResponseBody some of my methods can return JSON via Jackson - to Ajax calls. Again all is good:
<!-- to generate JSON responses using Jackson (without using <mvc:annotation-driven/>) -->
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
The problem is that now my explicit mappings defined in the SimpleUrlHandlerMapping bean are no longer working:
[http-8081-Processor25] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/mayapp].[springapp] - Servlet.service() for servlet springapp threw exception
javax.servlet.ServletException: No adapter for handler [com.mycom.controller.mySpring25Controller ...]: Does your handler implement a supported interface like Controller?
at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:985)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:773)
These mappings still appear in my log at start-up (SimpleUrlHandlerMapping - Mapped URL path ... etc) - but evidently are now broken somehow.
INFO org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/path/name.ext] onto handler [com.mycom.controller.mySpring25Controller ....]
I started with <mvc:annotation-driven/> which had the same problem. I've tried re-ordering without success, including order properties. And I've also not found an explanation in the Spring docs. It seems there is some interaction in the Spring auto-magic which I haven't got to the bottom of.
Interesting problem anyone? Insight gratefully received!
Post and ye shall find (delayed by 8 hours for lack of reputation)!
As per post No adapter for handler exception the answer appears to be that the explicit AnnotationMethodHandlerAdapter definition blows away the implicit SimpleControllerHandlerAdapter which was previously satisfying the SimpleUrlHandlerMapping mappings.
So add it explicitly:
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
</bean>
And we're good, though at the same time you might also need to introduce also an explicit replacement for the implicit HttpRequestHandlerAdapter also blown away:
<bean
class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter">
</bean>

Resources