Spring don't see controller - java

I have a problem with my spring MVC app. My app don't see my controller when i try to pass data between spring controller and angular controller.
Spring configuration:
web.xml
<?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>PiManager</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
<mvc:annotation-driven />
<context:component-scan base-package="org.inz.controller" />
<jpa:repositories base-package="org.inz.repositories"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
My services.js
PiManager.services.main = [ '$http', '$rootScope', '$state', function($http, $rootScope, $state) {
var self = this;
self.getTestEntity = function(id) {
return $http.get("/PiManager/index/"+id);
}
} ];
app.service('mainService', PiManager.services.main);
My controller.js
"use strict"
PiManager.controllers = {};
PiManager.controllers.main =
['mainService', '$scope', '$state', '$http', function(mainService, $scope, $state, $http) {
$scope.getTest = function(id) {
mainService.getTestEntity(id).then(function(response) {
$scope.testEntityPart = response;
});
}
}];
app.controller('mainController', PiManager.controllers.main);
My spring MainController
#Controller
#RequestMapping("/PiManager/")
public class MainController {
#Autowired
private TestEntityRepository testEntityRepository;
#RequestMapping(value = "/main")
public String index() {
return "/index.jsp";
}
#ResponseBody
#RequestMapping(value = "/index/{id}", method = RequestMethod.GET)
public List<TestEntity> getTestEntity(#PathVariable("id") Long id) {
return testEntityRepository.findById(id);
}
}
So when i type http://localhost:8080/PiManager/index/1 I got
GET http://localhost:8080/PiManager/index/1 404 (Not Found)
And i don't realy know what to do to make it work.

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

Related

Properly configure dispatcher-servlet, applicationContext and web.xml

First time using Spring (and new to MVC architecture as well) and Apache Tomcat and I'm able to load my index just fine after following a few videos/tutorials, but now that I'm trying to add other pages, I keep getting a 404 error. Here's what I have so far and the project structure is below as well for reference. The mapping of resources also seems to not be working as my index isn't loading images/js/etc.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.hackathon_10_20.EasySub.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/theme/startbootstrap-new-age-gh-pages/" cache-period="31556926"/>
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
IndexController.java
package org.hackathon_10_20.EasySub.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Created by Chris Bonilla on 10/20/2018.
*/
#Controller
public class IndexController {
#GetMapping("/")
public String index(Model m) {
m.addAttribute("someAttribute", "someValue");
return "index";
}
}
SubPlanController.java
package org.hackathon_10_20.EasySub.controller;
import org.hackathon_10_20.EasySub.domain.SubPlan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
import java.util.HashMap;
#Controller
public class SubPlanController {
Map<Long, SubPlan> subPlanMap = new HashMap<>();
#RequestMapping(value ="/subplan", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("subPlanHome", "SubPlan", new SubPlan());
}
#RequestMapping(value = "/subplan/{Id}", produces = { "application/json", "application/xml"}, method = RequestMethod.GET)
public #ResponseBody SubPlan getSubPlanById(#PathVariable final long Id) {
return subPlanMap.get(Id);
}
#RequestMapping(value = "/addSubPlan", method = RequestMethod.POST)
public String submit(#ModelAttribute("SubPlan") final SubPlan subplan, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
//model.addAttribute("name", subplan.getName());
//subPlanMap.put(subplan.getId(), subplan);
return "subPlanView";
}
}
You're missing a url-pattern value in your web.xml. It is empty.
Just change it to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Error creating bean with name 'userServicesDao': Unsatisfied dependency expressed through field 'connectionPool';

Hi I am new to Spring Framework. I am just creating POC to learn Spring Concepts. While implementing the same i am getting below exception while loading of application. Please provide me you suggestions to resolve this.
"Error creating bean with name 'userServicesDao': Unsatisfied dependency expressed through method 'setDbConfiguration' parameter 0"
UserServicesDao
package com.pe.dao;
#Component
public class UserServicesDao {
private DBConfiguration dbConfiguration;
#Autowired()
public void setDbConfiguration(DBConfiguration dbConfiguration) {
this.dbConfiguration = dbConfiguration;
}
public List<User> getUser()
{
System.out.println("User Services Dao : "+this.toString());
System.out.println("Connection Info : "+this.dbConfiguration);
return new ArrayList<User>();
}
#Override
public String toString() {
return "UserServicesDao [connection Config=" + dbConfiguration + "]";
}
}
ConnectionConfig.Java
package com.pe.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#Component(value ="dbConfiguration")
public class DBConfiguration {
#Value("com.mysql.jdbc.Driver")
private String driver;
#Value("jdbc:mysql://localhost:3306/mydb")
private String url;
#Value("root")
private String username;
#Value("root")
private String password;
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.pe.controller,com.pe.dao,com.pe.bean" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/jsp/</value>
</property>
<property name="suffix" value=".jsp">
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Web.xml
<web-app 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/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/spring</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/predictenergy/bean/dao-config.xml</param-value>
</context-param>
</web-app>
Click to see Class Folder Structure
It was autowiring before correction if i was doing it through xml. Please refer below xml code i was using before.
<bean id ="userServicesDao" class="com.pe.dao.UserServicesDao" autowire="byType">
<property name="dbConfiguration" ref= "dbConfiguration"></property>
</bean>
<bean id ="dbConfiguration" class ="com.pe.bean.DBConfiguration">
<property name="driver" value= "com.mysql.jdbc.Driver"></property>
<property name="url" value= "jdbc:mysql://localhost:3306/mydb"></property>
<property name="username" value= "root"></property>
<property name="password" value= "root"></property>
</bean>
Please guide me with your solution.

Getting 415 error while trying to call rest post method using spring

I am trying to implement spring rest method with post type. I am trying to retrieve JSON and convert it into java object. And returning with JSON only. Here is my code
package com.restService
#RestController
#RequestMapping(value="/user")
public class UserRestController {
#RequestMapping(value = "/post/create", method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON)
public #ResponseBody ResponseEntity<String> authenticateMobUser(#RequestBody User objUser) {
String result = null;
result = createUser(objeUser);
return new ResponseEntity<String>(result, HttpStatus.OK);
}
private String createUser(User objUser) {
// My create user code here
return "{\"status\":\"SUCCESS\",\"message\":\"SUCCESS\"}";
}
}
public class User {
String id;
String name;
// Getter and setters are present
}
Here is Spring configurations
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<tx:annotation-driven/>
<context:component-scan base-package="com.restService" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter"/>
</list>
</property>
</bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</beans>
Here is my web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>UserManagement</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springServlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Finally here is rest client I am using to call service
Client client = Client.create();
String strURL = null;
String domainName = "http://localhost:8080";
strURL = domainName + "/UserManagement/user/post/create";
String input = "{\"id\":\"12345\",\"name\":\"navnath\"}";
WebResource webResource = client.resource(strURL);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
When I run this code, I received "415 unsupported media type". while sending and retrieving, I am using MediaType.APPLICATION_JSON still getting this error.
Surly I am doing something wrong here but what it is, not getting
Don't you have to use MediaType.APPLICATION_JSON_VALUE in your RequestMapping?
Also, try to use RestTemplate instead of client if it is possible.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String input = "{\"id\":\"12345\",\"name\":\"navnath\"}";
HttpEntity<String> entity = new HttpEntity<>(input, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("/user/post/create", entity, String.class);
if (responseEntity.getStatusCode().value() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ responseEntity.getStatusCode().getReasonPhrase());
}
P.S. To solve the issue replace your AnnotationMethodHandlerAdapter in spring config with .

JavaConfig No bean named 'springSecurityFilterChain' is defined

I followed tutorial on http://shazsterblog.blogspot.com.es/2014/07/spring-security-custom-filterchainproxy.html to create a security filter using Java configuration instead of XML.
The bean is not being created and the application fails to load:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:323)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:234)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:332)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:90)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3783)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4409)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
This is the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>COMUN</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
</web-app>
This is the SecurityConfig class:
#Configuration
#EnableWebMvc
public class SecurityConfig extends WebMvcConfigurerAdapter implements ResourceLoaderAware{
private ResourceLoader resourceLoader;
#Bean
public FilterChainProxy springSecurityFilterChain() throws Exception {
AuthenticationManager am = authenticationManager();
SecurityContextPersistenceFilter sif = getSecurityContextPersistenceFilter();
J2eePreAuthenticatedProcessingFilter j2eePreAuthFilter = getJ2eePreAuthenticatedProcessingFilter(am);
LogoutFilter logoutFilter = getLogoutFilter();
ExceptionTranslationFilter etf = getExceptionTranslationFilter();
FilterSecurityInterceptor fsi = getFilterSecurityInterceptor(am);
FilterChainProxy fcp = new FilterChainProxy(new DefaultSecurityFilterChain(
new AntPathRequestMatcher("/**"),
sif, j2eePreAuthFilter, logoutFilter, etf, fsi
));
return fcp;
}
private FilterSecurityInterceptor getFilterSecurityInterceptor(AuthenticationManager am) {
AccessDecisionVoter<Object> roleVoter = new RoleVoter();
List<AccessDecisionVoter> decisionVoters = new LinkedList<AccessDecisionVoter>();
decisionVoters.add(roleVoter);
AffirmativeBased httpRequestAccessDecisionManager = new AffirmativeBased(decisionVoters);
httpRequestAccessDecisionManager.setAllowIfAllAbstainDecisions(false);
FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
filterSecurityInterceptor.setAuthenticationManager(am);
filterSecurityInterceptor.setAccessDecisionManager(httpRequestAccessDecisionManager);
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
List<ConfigAttribute> configs = new ArrayList<ConfigAttribute>();
configs.add(new org.springframework.security.access.SecurityConfig("hasRole(ADMIN)"));
requestMap.put(new AntPathRequestMatcher("/**"), configs);
FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
filterSecurityInterceptor
.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
return filterSecurityInterceptor;
}
private LogoutFilter getLogoutFilter() {
org.springframework.security.web.authentication.logout.LogoutFilter logoutFilter = new LogoutFilter("/", new SecurityContextLogoutHandler());
return logoutFilter;
}
private ExceptionTranslationFilter getExceptionTranslationFilter() {
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
new Http403ForbiddenEntryPoint());
return exceptionTranslationFilter;
}
private SecurityContextPersistenceFilter getSecurityContextPersistenceFilter() {
return new org.springframework.security.web.context.SecurityContextPersistenceFilter();
}
private J2eePreAuthenticatedProcessingFilter getJ2eePreAuthenticatedProcessingFilter(AuthenticationManager am) throws Exception {
WebXmlMappableAttributesRetriever mappableRolesRetriever = new WebXmlMappableAttributesRetriever();
mappableRolesRetriever.setResourceLoader(this.resourceLoader);
mappableRolesRetriever.afterPropertiesSet();
SimpleAttributes2GrantedAuthoritiesMapper userRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
userRoles2GrantedAuthoritiesMapper.setConvertAttributeToUpperCase(true);
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
= new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setMappableRolesRetriever(mappableRolesRetriever);
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setUserRoles2GrantedAuthoritiesMapper(userRoles2GrantedAuthoritiesMapper);
J2eePreAuthenticatedProcessingFilter j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(am);
j2eePreAuthenticatedProcessingFilter.setAuthenticationDetailsSource(j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource);
return j2eePreAuthenticatedProcessingFilter;
}
#Bean
public AuthenticationManager authenticationManager() throws Exception {
PreAuthenticatedGrantedAuthoritiesUserDetailsService preAuthenticatedGrantedAuthoritiesUserDetailsService = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();;
PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider = new PreAuthenticatedAuthenticationProvider();
preAuthenticatedAuthenticationProvider.setPreAuthenticatedUserDetailsService(preAuthenticatedGrantedAuthoritiesUserDetailsService);
List<AuthenticationProvider> lProviders = new LinkedList<AuthenticationProvider>();
lProviders.add(preAuthenticatedAuthenticationProvider);
AuthenticationManager am = new ProviderManager(lProviders);
return am;
}
#Override
public void setResourceLoader(ResourceLoader arg0) {
this.resourceLoader = arg0;
}
}
Any help please?
Bit different from the example and simplified for this case, the filter class is created if its package is set on component-scan
The following part of the web.xml is not needed:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
The web.xml defines the application context which will scan the class and create an instance of the filter. Later the instance is used in the web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context-${environment}.xml</param-value>
</context-param>
If the ${environment} variable is "DEV", it uses an application context that has the security defined in XML, if the ${environment} variable is "PRO", it uses the following application context which has the logic defined in Java:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd>
<context:component-scan base-package="com.config" />
</beans>
The filter only needs created in PRO so it needs the component-scan only for its package from within the application-context used in PRO.

Tomcat/ApplicationContext not able to find out Filter class

web.xml
<?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/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Self Service Portal</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>login</filter-name>
<filter-class>com.app.api.filter.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Spring Context Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
</web-app>
Custom filter class:-
package com.app.api.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebFilter("/*")
public class AuthenticationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
public AuthenticationFilter() {
System.out.println("Authentication - default filter !");
}
public void destroy() {
System.out.println("Authentication - destroy !");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
LOGGER.debug("Request authentication!");
HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
if(uri.equals("/app-api/login") || uri.equals("/app-api/logout")) {
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if(session == null || session.getAttribute("user") == null) {
writeInvalidCredentialResponse((HttpServletResponse) response);
} else {
chain.doFilter(request, response);
}
}
private void writeInvalidCredentialResponse(HttpServletResponse response) throws IOException {
Map<String, String> errorResponse = new HashMap<String, String>();
errorResponse.put("message", "Please login with right credentials!");
ObjectMapper mapper = new ObjectMapper();
String responseMessage = mapper.writeValueAsString(errorResponse);
LOGGER.debug("Invalid request authentication!");
LOGGER.debug(responseMessage);
response.getWriter().write(responseMessage);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Authentication - init !");
}
}
Project hierarchy:-
A - parent maven module
B - RESTful webservices sub module (contains - /WEB-INF/web.xml, /WEB-INF/dispatcher-servlet.xml)
C - persistence layer sub module (contains - /resources/applicationContext.xml, /resources/persistence.xml)
Please help me to resolve this issue to make my both spring context up and running (ui - webservices and persistence)
Many thanks in advance !
app-api
/app-api/src/main/webapp/WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="classpath:/applicationContext-data.xml" />
<context:annotation-config />
<context:component-scan base-package="com.app" />
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven/>
</beans>
app-data
/app-data/src/main/resources/applicationContext-data.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- ************* JPA/Hibernate configuration ************* -->
<bean
name="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.data.*" />
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="persistence-unit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/app"
p:username="root"
p:password="root123"
p:initialSize="5"
p:maxActive="10">
</bean>
<context:component-scan base-package="com.app.data.*" />
<tx:annotation-driven />
</beans>
Let's see the exception:
java.lang.ClassNotFoundException: com.adobe.ssp.api.filter.AuthenticationFilter
There was a problem with your classpath, the class "com.adobe.ssp.api.filter.AuthenticationFilter" was not found. Please make sure this class is contained in: YOUR_APP\WEB-INF\classes or YOUR_APP\WEB-INF\lib
Try removing #WebFilter and make sure about your init method overriding as we can't see that in code provided.

Categories

Resources