Placement css, img and js of files after deploy spring mvc application - java

I'm new in spring mvc, and I have some questions:
1) Can I get access to img, css and js inside WEB-INF directory from jsp page?
Folder structure is:
webapp
- WEB-INF
- css
- js
- img
2) I have the class WebMvcConfig, extending WebMvcConfigurerAdapter:
#Configuration
#EnableWebMvc
#Import({BeanConfig.class, CacheConfig.class})
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/resources/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ControllerInterceptor());
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public ContentNegotiatingViewResolver getContentNegotiatingViewResolver() {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
ArrayList<View> defaultViews = new ArrayList<View>();
MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
jsonView.setPrefixJson(true);
defaultViews.add(new MappingJacksonJsonView());
resolver.setDefaultViews(defaultViews);
resolver.setOrder(1);
return resolver;
}
#Bean
public ControllerInterceptor getLoggingInterceptor() {
return new ControllerInterceptor();
}
}
I want to get access to folders: /resources/css, /resources/img and /resources/js,
Part of web.xml file:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
config.WebMvcConfig
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Folder structure is:
webapp
- WEB-INF
- resources
- css
- js
- img
But it does not worked

Yes, you can do this.
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
And you have this structure
webapp
- WEB-INF
- resources
- css
- somefile.css
- js
- img
You would access your resources at
localhost:8080/context/css/somefile.css
will get the resource from /resources/css/somefile.css. Do the same for all the other resources.

Related

Legacy Spring MVC to Spring Boot

I have a legacy application which uses web.xml configuration.
The web.xml looks something like this.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/common-beans-context.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcherOne</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherOne-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherOne</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dispatcherTwo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherTwo-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherTwo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
To Convert this to Spring Boot Application,
I have done the below changes:
#Bean
public XmlWebApplicationContext xmlWebApplicationContext() {
XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
applicationContext.setConfigLocations("classpath:spring/common-beans-context.xml");
applicationContext.refresh();
return applicationContext;
}
#Bean
public ServletRegistrationBean<DispatcherServlet> mvcTestServlet(XmlWebApplicationContext applicationContext) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// create child application context
XmlWebApplicationContext childApplicationContext = new XmlWebApplicationContext();
childApplicationContext.setConfigLocation("classpath:spring/dispatcherOne-context.xml");
// set parent from the previous method
childApplicationContext.setParent(applicationContext);
dispatcherServlet.setApplicationContext(childApplicationContext);
childApplicationContext.refresh();
ServletRegistrationBean<DispatcherServlet> servletRegistrationBean = new ServletRegistrationBean<DispatcherServlet>(
dispatcherServlet, "/test/*");
servletRegistrationBean.setName("dispatcherOne");
servletRegistrationBean.addUrlMappings("/test/*");
servletRegistrationBean.setLoadOnStartup(1);
return servletRegistrationBean;
}
#Bean
public ServletRegistrationBean<DispatcherServlet> mvcServlet(XmlWebApplicationContext applicationContext) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// similar to the previous method..
// 1. create local applicationContext and then set parent.
}
I added childApplicationContext.refresh() to see if the beans were loading properly but what i think is happening is that the two dispatcher servlets are not able to access the beans defined in the parentContext. and are throwing beans not found exception even though they're available in parentContext
Is there a workaround for this?
or is there any other way I can achieve this ?
To create a Spring Boot application and re-using your existing config do the following and don't create a context yourself. You are basically trying to outsmart or work-around Spring Boot with what you are currently doing.
Create a class annotated with #SpringBootApplication and use #ImportResource to let Spring Boot creat the main application context.
#SpringBootApplication
#ImportResource("classpath:spring/common-beans-context.xml")
public YourApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(YourApplication.class);
}
}
Now as you have 2 DispatcherServlets in your original config you need to add 2 ServletRegistrationBean to set the URL etc.
#Bean
public ServletRegistrationBean<DispatcherServlet> dispatcherServletOneRegistration() {
ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean(new DispatcherServlet(), "/test/*");
registration.setLoadOnStartup(1);
registration.setName("dispatcherOne");
registration.setInitParameters(Collections.singletonMap("contextConfigLocation", "classpath:spring/dispatcherOne-context.xml");
return registration;
}
And more or less the same for the second servlet.
#Bean
public ServletRegistrationBean<DispatcherServlet> dispatcherServletTwoRegistration() {
ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean(new DispatcherServlet(), "/");
registration.setLoadOnStartup(1);
registration.setName("dispatcherTwo");
registration.setInitParameters(Collections.singletonMap("contextConfigLocation", "classpath:spring/dispatcherTwo-context.xml");
return registration;
}

No bean named 'springSecurityFilterChain' available

I am getting error
No bean named 'springSecurityFilterChain' available
when I don't include spring security configuration my code works fine. This project is created using spring annotation based configuration. When I created project using Maven pom.xml, web.xml, MvcConfiguration automatically gets created. Now I want to implement Spring-security with the same project and configuration. My configuration files are shown below.
MvcConfiguration.java
#Configuration
#ComponentScan(basePackages="com.mywebsite.emusicstore")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
Long maxUploadSize = 2048000L;
resolver.setMaxUploadSize(maxUploadSize);
return resolver;
} }
SpringSecurity.java
#Configuration
#EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin**").access("ROLE_USER")
.and().formLogin().loginPage("/login").defaultSuccessUrl("/admin/").failureUrl("/login?error").usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout");
//http.csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
HibernateConfig hc = new HibernateConfig();
String authoritiesByUsernameQuery = "SELECT username,authorities FROM authorities WHERE username = ?";
String usersByUsernameQuery = "SELECT username,password,enabled FROM users WHERE username = ?";
auth.jdbcAuthentication().dataSource(hc.dataSource()).authoritiesByUsernameQuery(authoritiesByUsernameQuery).usersByUsernameQuery(usersByUsernameQuery);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>emusicstore</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mywebsite.emusicstore</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Error
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1086)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:327)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:236)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4598)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please add this class as well.
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}

Spring 4 #Scheduled Task is executing task twice

I'm trying to execute some task every X second but the task runs twise. I'm Using Spring 4.2.5 - the latest version.(I tryed it with 4.05 the same result)
#Service
#Transactional
#EnableScheduling
public class PaymentServices {
#Autowired
private MMTransactionDAO mmTransactionDAO;
#Scheduled(fixedDelay=230000)
public void getListOfPenddingTransactions() throws MambuApiException {
System.out.println("JOB Started");
List<MMPayTransaction> listOfPenddingTransaction = mmTransactionDAO.getListOfPenddingTransaction();
for(MMPayTransaction transaction : listOfPenddingTransaction){
if (transaction.getErrorcode().equals("-6")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if(transaction.getErrorcode().equals("-21")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if(transaction.getErrorcode().equals("-18")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if (transaction.getErrorcode().equals("-37")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}
else{
check(transaction.getOperationID());
}
}
}
}
here is my web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
UPDATED
here is my application configuration calss:
#EnableWebMvc
#Configuration
#ComponentScan({"ge.kapi.*"})
#EnableTransactionManagement
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);
factory.setDataSource(dataSource());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("ge.kapi");
Properties jpaProperties = getHibernateProperties();
factory.setJpaProperties(jpaProperties);
factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect","ge.kapi.config.SQLServerUnicodeDialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
ds.setUrl("jdbc:sqlserver://host;useUnicode=true;characterEncoding=UTF-8;DatabaseName=Base");
ds.setUsername("user");
ds.setPassword("pass");
return ds;
}
#Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
#Bean
public PlatformTransactionManager transactionManager()
{
EntityManagerFactory factory = entityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setContentType("text/html; charset=UTF-8");
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Why is it running TWICE each time?
Thanks in advance
-- Found Solution --
I have removed #ComponentScan({"ge.kapi.*"}) from AppConfig.java because this scan was also initiated from mvc-dispatcher-servlet.xml like this:
<context:component-scan base-package="ge.kapi"/>
Now Job starts only ones.
Thank you all for your time helping me!!!
I suggest you check if the bean is being created twice. It can happen if you have 2 app contexts (root and dispatcher).
Check if you have declared bean in xml and by annotation too.
And if you have spring security configuration in your application then keep mvc-dispatcher.xml declaration in of DispatcherServlet and spring-security.xml in of context loader listener .
Otherwise if you keep both xml with DispatcherServlet in that case two object will be created and that is why your scheduler will get call twice.

Wildfly resteasy javax.ws.rs.NotFoundException

i know that this post is duplicate and there are a lot of solutions yet, but i wasn't able to use them to resolve the problem.
I am trying to use spring + wildflyAS + resteasy. I have problems with resteasy integration, here is error which i am getting while trying to access controller:
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/BQP/rest/student/test/1/pass/1
Controller:
#Controller
#RequestMapping(value = "student")
public class StudentController {
#Autowired
StudentService studentService;
public StudentController() {
}
#RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
#ResponseBody
Response getCurrentTest(#PathVariable("id") String id,#PathVariable("testId") String testId){
TestDTO testDTO = studentService.getCurrentTest(id,testId);
return Response.status(200).entity(testDTO).build();
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>BQP</display-name>
<!--Spring-->
<servlet>
<servlet-name>Spring MVC Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--/Spring-->
<!--RestEASY-->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.bionic.rest.ApplicationConfiguration</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<!--/RestEASY-->
ApplicationConfiguration:
package com.bionic.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class ApplicationConfiguration extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ApplicationConfiguration() {
singletons.add(new StudentController());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Moreover, i can access this controller without /rest in url.

how to convert site minder xml configuration using Spring4 Java config

I am converting an old version based Spring application to annotation based Spring4 application. As a first step I converted all xmls to java configuration based annotations. The application is working fine, but the only issue is with the site minder xml configuration. I don't know how to convert the below siteminder configuration which is there in the web.xml into java based.
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>SiteMinderRealm</realm-name>
</login-config>
The above siteminder configuration is in web.xml,
Can anyone please tell me how to write the java based configuration for the above xml in AppInitializer.java
my web.xml and its corresponding substituted AppInitializer.java code is as shown below
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>SpringWebMVCApp</display-name>
<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.helloworld.config.AppConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/rest/</url-pattern>
</servlet-mapping>
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>SiteMinderRealm</realm-name>
</login-config>
</web-app>
AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/rest/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
return context;
}
}
Update 1
public class AppInitializer extends WebSecurityConfigurerAdapter implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/rest/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
return context;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName("SiteMinderRealm").and().x509();
}
}
Did you try configuring this on the WebSecurityConfigurerAdapter? Something like this:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName("SiteMinderRealm").and().x509();
}
}

Categories

Resources