Redis session created, but attributes are stored locally - spring

After accessing a webpage, a session is created in redis, but the attribute values that I set do not show up. Also, the sessions variables that I set persist if I remove the session from the database, meaning the attributes are being stored locally.
pom.xml
<org.springframework-version>4.1.6.RELEASE</org.springframework-version>
<spring-webmvc-version>4.0.0.RELEASE</spring-webmvc-version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- --> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<!-- -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
myFilter
#Component(value = "myFilter")
public class myFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(SessionVerificationFilter.class);
public static ClassPathXmlApplicationContext context;
#Autowired
private Environment env;
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)res;
logger.info("Host Name in SessionVerificationFilter: "+request.getServerName());
printSession(request);
printHeaders(request);
request.getSession().setAttribute("test", "test");
...
context.xml
<!-- -->
<beans:bean id="RedisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />
<beans:bean
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:port="6379" />
<bean id="httpSessionStrategy"
class = "org.springframework.session.web.http.CookieHttpSessionStrategy"
p:cookieName="SAMSessionId"/>
<bean
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"
p:httpSessionStrategy-ref="httpSessionStrategy" />
web.xml
<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
After running hgetall on my session:
127.0.0.1:6379> hgetall spring:session:sessions:469e415a-4b03-4038-8777-4d292bf1
5474
1) "maxInactiveInterval"
2) "\xac\xed\x00\x05sr\x00\x11java.lang.Integer\x12\xe2\xa0\xa4\xf7\x81\x878\x02
\x00\x01I\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b
\x02\x00\x00xp\x00\x00\a\b"
3) "creationTime"
4) "\xac\xed\x00\x05sr\x00\x0ejava.lang.Long;\x8b\xe4\x90\xcc\x8f#\xdf\x02\x00\x
01J\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b\x02\x
00\x00xp\x00\x00\x01R\x8eC\xa15"
5) "lastAccessedTime"
6) "\xac\xed\x00\x05sr\x00\x0ejava.lang.Long;\x8b\xe4\x90\xcc\x8f#\xdf\x02\x00\x
01J\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b\x02\x
00\x00xp\x00\x00\x01R\x8eC\xa15"
127.0.0.1:6379>

Related

Can't solve this issue UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl

i've tried alot to fix this issue but couldn't. I find, if we use "abstractBinder" then this could be fix but once i've my Binder in place, i start having 404 error.
UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl
Please help
My Resource:
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.walmart.services.helpers.IUserService;
import com.walmart.services.helpers.ServicesTest;
#Path("/sayHello")
public class ControllerTest {
#Inject
private IUserService service;
#Inject
private ServicesTest service2;
#GET
#Path("/{name}")
#Produces(MediaType.TEXT_PLAIN)
public String method(#PathParam("name") String msg) {
return service.method() + " msg";
}
#GET
#Path("/v2/{name}")
#Produces(MediaType.TEXT_PLAIN)
public String method2(#PathParam("name") String msg) {
return service2.method() + " msg";
}
}
My resource configuration file:
#ApplicationPath("/rest/*")
public class ResourceConfiguration extends ResourceConfig {
public ResourceConfiguration() {
//register(new MyBinder());
this.packages(true, "com.walmart.services.*");
}
}
My Binder [ if in place ]
public class MyBinder extends AbstractBinder
{
#Override
protected void configure() {
// TODO Auto-generated method stub
bind(new ServicesTest()).to(ServicesTest.class);
// bind(UserServiceImpl.class).to(IUserService.class).in(RequestScoped.class);
}
}
Services:
IUserService and its implementation
public interface IUserService {
public String method();
}
public class UserServiceImpl implements IUserService {
#Inject
public UserServiceImpl() {
System.out.println("test");
}
#Override
public String method() {
return "Welcome ";
}
}
Other
public class ServicesTest {
public ServicesTest() {
System.out.println("created ");
}
public String method() {
return "Welcome";
}
}
WEbXML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>com.walmart.learning.javaee</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Now, i can access my resource using
http://localhost:8080/javaeeLearning/rest/sayHello/h
Which gives me below errors
SEVERE: Servlet.service() for servlet [com.walmart.configuration.ResourceConfiguration] in context with path [/javaeeLearning] threw exception [A MultiException has 4 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=IUserService,parent=ControllerTest,qualifiers={},position=-1,optional=false,self=false,unqualified=null,2007960340)
2. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=ServicesTest,parent=ControllerTest,qualifiers={},position=-1,optional=false,self=false,unqualified=null,10615079)
3. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.walmart.services.rest.controller.ControllerTest errors were found
4. java.lang.IllegalStateException: Unable to perform operation: resolve on com.walmart.services.rest.controller.ControllerTest
] with root cause
And to resolve, i uncomment my Binder in Resource configuration
then i start having 404.
Please help....
Other details;
Pom
<name>javaeeLearning</name>
<properties>
<maven.compiler.source>10</maven.compiler.source>
<maven.compiler.target>10</maven.compiler.target>
<jaxrs.version>2.0.1</jaxrs.version>
<jersey2.version>2.23</jersey2.version>
<jersey2.gf.cdi.version>2.14</jersey2.gf.cdi.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${jaxrs.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</dependency>
<!-- Jersey2.x Dependencies -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- Jersey2.x Dependency injection -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.inject/jersey-hk2 -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-core -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.4.0-b180830.0438</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>${jersey2.gf.cdi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
Make your JAX-RS resource a CDI bean like this:
#Path("/sayHello")
#RequestScoped
public class ControllerTest {
Then you don't need the Binder and injection should work.
You could set bean discovery mode to all in beans.xml:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
or annatate UserServiceImpl with an scope annotation (like #Dependent)

Spring MVC 5 & Tomcat 9 - Unable to render the model attribute in the JSP [duplicate]

This question already has answers here:
EL expressions not evaluated in JSP
(5 answers)
Closed 5 years ago.
I want to pass the model attribute to the JSP file and print it using the appropriate JSTL tags. When I call the /home, all I see is the tag I used to be placeholder (${name}) for the attribute; not the value I have set.
Here is my controller:
#Controller
#RequestMapping(value = "/*")
public class MainController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public void home(Model model) {
model.addAttribute("name", "John");
}
}
The WebConfig class which implements WebMvcConfigurer
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.tk"})
public class WebConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
WebAppInitializer class
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) {
AnnotationConfigWebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.addMapping("/");
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
servletContext.addFilter("characterEncodingFilter", characterEncodingFilter).addMappingForUrlPatterns(null, false, "/*");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.tk.spring5App.config");
return context;
}
}
home.jsp file content:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<body>
<h1><c:out value="${name}"/></h1>
</body>
</html>
And finally here is my pom.xml file:
<properties>
<java.version>1.8</java.version>
<spring.framework.version>5.0.3.RELEASE</spring.framework.version>
</properties>
<dependencies>
<!-- **********************************************************************
** SPRING DEPENDENCIES **
********************************************************************** -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!--javax.servlet-api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<!--<scope>runtime</scope>-->
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--javax.xml-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
The web app is hosted on Apache Tomcat 9.0.4.
You probably have a (possible empty) web.xml with a version of 2.4 or lower in there. With that version evaluating EL expressions is disabled by default and as such expressions will show up as regular text.
Now you have 2 options either switch to a newer version 2.5
<web-app
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
or remove the web.xml altogether relying only on annotations. Beware that not everything can be configured through annotations as you can in the web.xml or with web-fragment.xml if you need those configuration options (like <distributable />, extensive session configuration etc.) you still need an XML configuration (but just make sure it has a proper version).

How to resolve java.lang.NoClassDefFoundError: org.springframework.web.filter.CorsFilter

I am trying to implement Oauth Security in Spring MVC.
this is my java based configuration :
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter{
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("jdbc/peoplecheck");
return dataSource;
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
THis is my pom :
<properties>
<spring.version>4.1.2.RELEASE</spring.version>
<jackson.version>1.9.13</jackson.version>
<javax.validation.version>1.1.0.Final</javax.validation.version>
<springsecurity.version>4.1.1.RELEASE</springsecurity.version>
<springsecurityoauth2.version>2.0.10.RELEASE</springsecurityoauth2.version>
<jackson.library>2.7.5</jackson.library>
</properties>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.version}</version>
</dependency>
<!-- <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency> -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Spring Security OAuth2-->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${springsecurityoauth2.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
I am using websphere application server. Whenever i try to run the application i get this exception and very confused what is missing.
if i go with only java based it works fine, while i need to implement in xml based or both as i cant change the entire project.
00000056 DispatcherSer E org.springframework.web.servlet.FrameworkServlet initServletBean Context initialization failed
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: org.springframework.web.filter.CorsFilter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:591)
... 109 more
Caused by: java.lang.NoClassDefFoundError: org.springframework.web.filter.CorsFilter
at org.springframework.security.config.annotation.web.builders.FilterComparator.<init>(FilterComparator.java:74)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.<init>(HttpSecurity.java:121)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:178)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:67)
at org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration$$EnhancerBySpringCGLIB$$91437efb.init(<generated>)
spring-security 4.1.1.RELEASE uses spring-framework version 4.3.1.RELEASE. Can you try updating your spring version?
http://docs.spring.io/spring-security/site/docs/4.1.1.RELEASE/reference/htmlsingle/#maven-bom
It seems your CorsFilter is not implemented properly. You should try this filter
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
LOG.info("Adding CORS Headers ........................");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
You can refer to the working example Cross Origin Request Blocked
Hope this help.

Upgrading to switch from JSON/XML marshalling in order to use Jackson 2

I am currently using Spring - and am using Jersey's old technologies to marshall and unmarshall - I need to upgrade the marshalling library to the latest version in order to use Jackson.
I have usually got some code to show, but obviously in this scenario - I am not even sure where to begin, so if anyone can help out that would be cool.
WEB.XML CONFIGURATION FOR JERSEY :
<servlet>
<description>Jersey Servlet</description>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
POM :
<jersey.version>1.4</jersey.version>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersey.version}</version>
<scope>runtime</scope>
<!-- exclude spring dependencies so can pin to our desired versions (esp. spring-web) -->
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
If you want to use Jackson 2, you should first get rid of the jersey-json, then add the following
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson2.version}</version>
<!-- latest right now is 2.8.3 -->
</dependency>
Then in your servlet configuration, add the Jackson package to the list of packages to scan.
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
your.packages,
com.fasterxml.jackson.jaxrs.json <!-- add jackson -->
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Note that if you are using a Jackson version newer than 2.7.0, the above package will not include the Jackson ExceptionMappers. According to this issue, it seems they are now removed and also the #Provider annotations have been removed. So we can't package scan for them.
So if you do want the mappers, you should declare them by class.
<param-name>
com.sun.jersey.config.property.classnames
</param-name>
<param-value>
com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper,
com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper
</param-value>
I should mention though, that it's really recommended to write your own mappers. The response the these mappers spit out, is the exception message, and that's not really something you want as the error response.
You will need to update your POM to include the jackson jars(core, databind, annotaion) in https://mvnrepository.com/artifact/com.fasterxml.jackson.core. You will also need to do the below for converting JSON to Java object and vice versa
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter" />
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
You would need to create a class with variables that are named after the "keys" in JSON. The code to convert JSON string to object of the JAVA class would be as below:
Suppose JSON is
{
'name' : 'Test',
'userId' : 'test101'
}
The Java class corresponding to this would be:
public class Test {
private String name;
private String userId;
// Write getter and setter methods for each variable.
}
The code for converting JSON string to the object of Test class would be:
ObjectMapper mapper = new ObjectMapper();
String jsonInString = ""{'name' : 'Test', 'userId' : 'test101'}"";
//JSON from String to Object
Test obj = mapper.readValue(jsonInString, Test.class);
obj.getName() would give value corresponding to the key.

Why is my session still alive

I am using spring with redis backed sessions.
If I access the site, I see that sessions is added to database.
Then I run flushdb on the database.
Then I try and access the site, and sessions is still alive (I have the same session id.) The redis keys are different, but the session id's are the same.
Is the session being stored somewhere else not in redis? Is this expected?
Using windows 64 bit redis 2.8.2400.
some pom dependencies.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
Relavent Beans
<beans:bean id="RedisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />
<beans:bean
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:port="6379" />
some web.xml
<listener>
<listener-class>com.mysite.listeners.sessionStarted</listener-class>
</listener>
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Controller function for closing session
RequestMapping(value = "/closeSession", method = RequestMethod.GET)
public String closeSession(HttpSession session, HttpServletRequest request) {
logger.info("Closeing Session (greri002 for testing).");
session.invalidate();
//request.logout();
SecurityContextHolder.getContext().setAuthentication(null);
return "OK";
}
Spring security is managing your sessions storing the data in redis. You only need to bring in something like redis if you're planning on being able to share session data between nodes.
Spring's SecurityContext where security info in stored.
https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/core/context/SecurityContext.html
Assuming you're using a server that supports 3.0 Servlets you just need to call logout() on a HttpServletRequest object. A spring MVC sample -
#RequestMapping(value="/me/logout", method=RequestMethod.GET)
public #ResponseBody String logout(HttpServletRequest request) throws ServletException {
request.logout();
return "OK";
}
http://docs.spring.io/spring-security/site/docs/3.2.1.CI-SNAPSHOT/reference/htmlsingle/#servletapi-logout
If you don't have access to HttpServletRequest you can do
SecurityContextHolder.getContext().setAuthentication(null);
Also make sure you have logout for the http config config'ed correctly. he's mine
<sec:logout logout-url="/logout"
delete-cookies="JSESSIONID,jsessionid"
invalidate-session="true"
success-handler-ref="myLogoutFilter"/>

Resources