My Spring release is 5.x and tomcat version is 8.5, so according to introduction, they will support the web application running without web.xml, but I got 404 error, see my project structure below:
I use this url to access my application, but got 404 error:
http://localhost:8080/SpringMVC/
see my code below:
RootConfig.java:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages= {"spitter"},
excludeFilters= {#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)}
)
public class RootConfig {
}
WebConfig.java:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig implements WebMvcConfigurer{
public ViewResolver viewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
SpittrWebAppInitializer.java:
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
HomeController.java:
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
System.out.println("test");
return "home";
}
}
home.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>this is the Home Jsp page</title>
</head>
<body>
<h1>Hello, Spring MVC!</h1>
</body>
</html>
from the Eclipse console, I can see output "test" that means spring context find out the controller, but seems it cannot find the jsp page, I don't know the reason, can someone tell me what's wrong with my code?
Try adding #Bean annotation on top of WebConfig#viewResolver() method. So, the Spring Container manage your method as bean and your custom configuration will probably work.
#Bean
public ViewResolver viewResolver(){}
Indicates that a method produces a bean to be managed by the Spring
container.
Related
I'm building a spring mvc application and include spring security for logging in and out, but when I add the context of the root 'TechZone' behind: "localhost: 8080 / TechZone / login" it doesn't work , it seems that the default security application only accepts "localhost: 8080 / login". How to correctly configure the servlet url customization, if anyone knows please help me and I appreciate it!
package com.techzone.springmvc.config;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableTransactionManagement
public class DatabaseConfig extends WebMvcConfigurerAdapter {
final static String PACKAGE_SCAN = "com.techzone.springmvc";
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", true);
properties.put("hibernate.format_sql", true);
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
#Bean(name = "dataSource")
public BasicDataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/TechZone?useSSL=false");
dataSource.setUsername("springstudent");
dataSource.setPassword("springstudent");
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactoryBean(BasicDataSource dataSource) {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setPackagesToScan(PACKAGE_SCAN);
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
// #Bean /** PersistenceJPAConfig **/
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
// factory.setDataSource(getDataSource());
// factory.setPackagesToScan(PACKAGE_SCAN);
// JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// factory.setJpaVendorAdapter(vendorAdapter);
// factory.setJpaProperties(hibernateProperties());
//
// return factory;
// }
// #Bean
// public HibernateTransactionManager transactionManager(SessionFactory session) {
// HibernateTransactionManager manager = new HibernateTransactionManager();
// manager.setSessionFactory(session);
// return manager;
// }
//
// #Bean
// public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
// return new PersistenceExceptionTranslationPostProcessor();
// }
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
// AUTO
}
package com.techzone.springmvc.config;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userDetailService")
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
.and().authorizeRequests()
.antMatchers("**/login").permitAll()
.antMatchers("/dashboard").hasRole("USER")
.and().formLogin().defaultSuccessUrl("/dashboard").loginProcessingUrl("/login")
.loginPage("/login").and().logout().permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
}
#Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
package com.techzone.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan({"com.techzone.springmvc"})
public class MvcConfig extends WebMvcConfigurerAdapter { // TODO INFO: This's the dispatcher servlet's Spring application context //
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/*.js/**").addResourceLocations("/views/static/");
registry.addResourceHandler("/*.css/**").addResourceLocations("/views/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resourceView = new InternalResourceViewResolver();
resourceView.setViewClass(JstlView.class);
resourceView.setPrefix("/views/jsp/");
resourceView.setSuffix(".jsp");
return resourceView;
}
// for upload image
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
// multiple Language
#Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
interceptorRegistry.addInterceptor(localeChangeInterceptor).addPathPatterns("/*");
}
}
package com.techzone.springmvc.config;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
// TODO : Create the root spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MvcConfig.class, DatabaseConfig.class,MessageResourcesConfig.class,SpringSecurityConfig.class);
// TODO : Manager life cycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
// TODO : Create the dispatcher servlet's spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(MvcConfig.class);
// TODO : Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
// TODO : Filter Character UTF-8
FilterRegistration.Dynamic filter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
filter.setInitParameter("encoding", "UTF-8");
filter.setInitParameter("forceEncoding", "true");
filter.addMappingForUrlPatterns(null, true, "/*");
}
}
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
isELIgnored="false" pageEncoding="UTF-8"%>
<html>
<head>
<title>Spring Security Example</title>
<link href="/bootstrap.min.css" rel="stylesheet">
<script src="/jquery-2.2.1.min.js"></script>
<script src="/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin: 50px;border: 1px solid green;">
<h3>Spring Security Login Example</h3>
<c:if test="${param.error ne null}">
<div style="color: red">Invalid credentials.</div>
</c:if>
<form action="/login" method="post">
<div class="form-group">
<label for="username">UserName:</label> <input type="text"
class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label> <input type="password"
class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-success">Submit</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</body>
</html>
**
I expect it work with localhost:8080/nameYourApp/login instead of localhost:8080/login
**
Pic1
Pic2
You can define, complete path for security login (new AntPathRequestMatcher("/TechZone/login"));
I am learning Spring Framework. I added home.html in resources/templates/home.html. But it is not visible when I visit http://localhost:8080. I have the following structure:
taco-cloud\src\main\java\tacos\TacoCloudApplication.java
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
taco-cloud\src\main\java\tacos\HomeController.java
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomeController
{
#GetMapping("/")
public String home()
{
return "home.html";
}
}
taco-cloud\src\main\resources\static\home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
<h1>Welcome to...</h1>
<img th:src="#{/images/TacoCloud.png}"/>
</body>
</html>
Output
Whitelable error page
localhost:8080/home.html
show home.html
You have to change the location of your home page to be in the static folder :
resources/static/home.html
^^^^^^
instead of
resources/templates/home.html
and specify the extension in your controller :
return "home.html";
^^^^^
else you have to create a view resolver to avoid using extensions and to specify the other locations of your pages take a look at Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error
You can try this.
#GetMapping("/")
public String home()
{
return "templates/home.html";
}
Check more details
Below are few different ways you can place html files in your project.(Note it is from highest to lowest precedence)
src/main/resources/resources/home.html
src/main/resources/static/home.html
src/main/resources/public/home.html
Go through this to get an idea about spring mvc project structure
I have configured all the settings for my spring project, but when I try to login in to the application, it says for each request that
"The server understood the request but refuses to authorize it."
Initially I tried to implement JDBC Authentication, (you can see that I am using the Datasource in my code). But then I tried with in memory authentication too, in both cases, I am unable to access the resources.
Below is my spring config file,
package com.nobalg.config;
import java.beans.PropertyVetoException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.nobalg")
#PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public DataSource secureDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
//Datasource
dataSource.setDriverClass(env.getProperty("jdbc.driver"));
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.password"));
//Connection polling
dataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
dataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
return dataSource;
}
}
Dispatcher Servlet Initializer file
package com.nobalg.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MvcSpringInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[]{AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
Spring security configuration file :
package com.nobalg.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.jdbcAuthentication().dataSource(dataSource);
auth.inMemoryAuthentication().withUser("Nobal").password("test#123").authorities("MANAGER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.loginProcessingUrl("/loginProcessing")
.usernameParameter("username")
.passwordParameter("password")
.permitAll();
}
}
Spring security initializer file
package com.nobalg.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
The one and only controller
package com.nobalg.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class MainContoller {
#GetMapping("/loginPage")
public String showLoginForm(){
return "login";
}
}
and the login page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="POST" action="${pageContext.request.contextPath}/loginProcessing">
<p>Enter Username : <input type="text" placeholder="Enter Username" name="username"></p>
<p>Enter Password : <input type="password" placeholder="Enter Password" name="password"></p>
<p><input type="submit" value="LOG IN"></p>
</form:form>
</body>
</html>
Add this as your form field:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Or if you want other approach with Spring Security JSP tag library:
Optionally you can disable csrf, which is enabled by default:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
Edit1
Add this bean with passwordEncoder.
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
And set password encoder to auth:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.passwordEncoder(this.passwordEncoder());
}
Edit2
Change .loginProcessingUrl("/loginProcessing") which needs UserDetailsService to .defaultSuccessUrl("/")
I'm actually learning Spring Boot. I follow the guides and i'm tryng this one : Securing a Web Application.
So I've made 2 files (hello.html/home.html) and i would like to deploy my application to see them but when i try to access localhost:8080 i get this error :
Circular view path [home]: would dispatch back to the current handler URL [/home] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
If someone can help me there ? Here is my code :
src/main/java/com/society/MyApplication :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(CalamarApplication.class, args);
}
}
src/main/java/com/society/MvcConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Thanks by advance.
I am getting this error while adding Assets folder.
It is giving error for every file which is included from "assets" folder.
WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/assets/plugins/datepicker/datepicker3.css] in DispatcherServlet with name 'dispatcher'
Here is the Dispacther Config file
package com.springmaven.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({"com.springmaven.controller"})
public class DispatcherConfig {
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver=new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/JSP/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
This is App Config
package com.springmaven.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class AppIntializer implements WebApplicationInitializer{
#Autowired
public void onStartup(ServletContext servletCon) throws ServletException {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationConfig.class);
servletCon.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletConfig = new AnnotationConfigWebApplicationContext();
servletConfig.register(DispatcherConfig.class);
ServletRegistration.Dynamic registration = servletCon.addServlet("dispatcher", new DispatcherServlet(servletConfig));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
This is security Config
package com.springmaven.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private AuthenticationProvider customAuthenticationProvider;
#Autowired
CustomSuccessHandler customSuccessHandler;
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/assets/**");
}
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(customAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/assets/**").permitAll()
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("username").passwordParameter("password")
.and().csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setSessionAttributeName("_csrf");
return repository;
}
}
Folder Structure
source->main->webapp->WEB-INF->JSP->assets(This folder is not recognised)
source->main->webapp->WEB-INF->JSP->homePage.jsp
From the Style or Icon is not coming in homePage.
homePage.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>New Member</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<!--Favicon Image -->
<link rel="shortcut icon" href="assets/dist/img/favicon.ico"/>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/plugins/datepicker/datepicker3.css">
</head>
<body>
Welcome,
<form id="logout" action="${Signout}" method="post" >
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
Logout
</c:if>
</body>
</html>
You need to add support for static web resources.
To configure it to be managed by Spring see this question, for example.