Problem with my mvc app isnt using style.css - css

Im trying to configure style css file with my mvc app. Everything is working well except that pages dont use style.css. Im doing it first time and i dont know how it should look like but i did this with internet. Where is a problem? :/
App config
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("spring")
#PropertySource({ "classpath:persistence-mysql.properties" })
public class AppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/views/");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
Head JSP file
<head>
<title>Site under construction</title>
<link href='<spring:url value="/resources/css/style.css"/>'>
</head>
Path to css file
\src\main\resources\css\style.css

Bring up the debug tools in your browser (F12 generally). You will most likely see a 404 for that file (missing). Check out what URL the browser is trying to pull the resource from. Most likely it's looking somewhere you aren't expecting.

Related

addResourceHandler #EnableWebMvc setup

My handler was working prior to some dependency updates and ditching of the XML in my app. But now I get this error
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /resources/img/logo.png
My view resolver is working fine, my controller is pointing to the right places it is just my css/js that doesn't seem to map.
public class ConfigClass {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
WebMvcConfigurationSupport appears to be essential.
public class ConfigClass extends WebMvcConfigurationSupport{
//Rest here
}
EDIT
The initial answer was based on an amateur "cached" answer. The actual solution was using
public class ConfigClass extends WebMvcConfigurerAdapter {
However, this is now deprecated. Am looking into an answer for that.

Spring MVC show image

I want to show image in my JSP page in my Spring MVC Project , but the images are not working.
The images are located in src/main/webapp/resources/images folder
Folder structure
Please find the code below. Any help will be appreciated:
#Configuration
#EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurationSupport {
// Resource reading from jsp
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Here I declare a mapping of src\main\webapp\resources folder and all its content to a resource location value /resources/
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
// Property reading from jsp
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/i18n/application");
return messageSource;
}
// View Resolver
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
In the jsp it is called as :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>
<body>
<img src="<c:url value='/resources/images/abc.jpg' />" >
</body>
</html>
based on our folder structure resource mapping is changed
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Here I declare a mapping of src\main\webapp\resources folder and all its
content to a resource location value /resources/
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
ResourceResolvers can resolve resources, given their URL path. They can also resolve the externally facing public URL path for clients to use, given their internal resource path.
XML configuration:
<mvc:resources mapping="/resources/**" location="/resources/"/>
Annotation Configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
Use in jsp:
<img src="/contextpath/resources/images/abc.jpg" >
Resource folder structure in project:
TestProject
|
src
|
WebContent
|
resources
|
js/css/images

Spring custom login page only showing in IDE

I am developing a REST-API with Spring Boot. Now I want to act as a OAuth2 provider as well and therefore I want to add support for the "client_credentials" grant type.
In order to do that I have to allow users to login and authorize the client. Spring provides an ugly default login form for doing that so now I want to show my own custom login form instead.
The problem is I can't get it to work outside my IDE.
My configuration looks as follows:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login")).and().authorizeRequests().antMatchers("/hellopage").hasAuthority(Role.USER.value())
.and().formLogin().defaultSuccessUrl("/hellopage").loginPage("/login").and().logout().permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
}
}
#Configuration
protected class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*.js/**").addResourceLocations("/ui/static/");
registry.addResourceHandler("/*.css/**").addResourceLocations("/ui/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/testpage").setViewName("testpage");
registry.addViewController("/hellopage").setViewName("hellopage");
}
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/ui/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
And my folder structure looks like this:
When I run my application inside Eclipse and visit http://localhost:8080/login everything works fine and my custom login form is shown. When I package my application with maven and execute the generated .war file, visiting http://localhost:8080/login shows the ugly default login form which leads me to believe that spring is unable to find the resources for my custom form.
When I try to access any other .jsp like testpage.jsp, I get the following error (this also works fine when the app is run from my IDE):
I am deploying my application using a docker container that runs the .war file using java -jar myserver.war, so this has to work for me.
How can I make sure Spring can find my provided resources when executing the .war file?
By default Maven expects a the jsp's in /WEB-INF/* location.
You can keep the jsp's in src/main/webapp/WEB-INF/jsp. Also you can update the InternalViewResolver prefix as well accordingly.
For detailed explanation you can refer https://stackoverflow.com/a/19786283/3981536

How do I set home.jsp as my welcome page in java config based spring application

I am developing a spring application (annotation based configurations) in which index.jsp is my default welcome page. but now I don't want to display index.jsp as my welcome page and want to change it to home.jsp. how can I achieve this?
I tried below method from WebMvcConfigurerAdapter class
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
it is not working.
You need to forward the default mapping. Hope this may help you!
#Configuration
public class YourViewClass extends WebMvcConfigurerAdapter
{
#Override
public void addViewControllers( ViewControllerRegistry registry )
{
registry.addViewController( "/" ).setViewName( "forward:/yourhomepage.html" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers( registry );
}
}

Configuring spring to return a static file on a Controller method

How do I say to Spring MVC to return a static resource at runtime(in a method)?
Explain better. I configured my application(spring-mvc 3.2.4) to deal with some static resource and to work with two view resolvers, FreeMaker and Json. I wish that in a controller method I would be able to say to spring-mvc that he must take the file in the static resource despite try hadle by one of views resolvers.
My configuration class looks like this:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.xxxx", excludeFilters = #Filter(Configuration.class)})
public class WebConfig extends WebMvcConfigurerAdapter {
...
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app.js").addResourceLocations("/app.js");
}
...
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
// Define the view resolvers
List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
JsonViewResolver jsonViewResolver = new JsonViewResolver();
FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
freeMarkerViewResolver.setSuffix("rtl");
resolvers.add(jsonViewResolver);
resolvers.add(freeMarkerViewResolver);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
resolver.setViewResolvers(resolvers);
return resolver;
}
}
My controller:
#Controller
#RequestMapping("/")
public class JSViewController {
#RequestMapping(value="*.js")
public String resolveArquivo(HttpServletRequest request){
// Here I would be able to say to sprint to return a static resource instead of hadle it with one of the View Resolvers.
return request.getRequestURI().replace(request.getContextPath(),"");
}
}
Its would be better if you try to access static and dynamic data seperately as hitting a controller for static data will waste your resources, increase latency.
For eg. if you want to access js from jsp then you can use JSTL tag library which would dynamically return the output directory from where you can fetch the static resource.
This gives you the flexibility to cache your static resources (Akamei or something else) or server them from apache instead of tomcat.
If you really want to render your static resource from controller then you need to have an interceptor which could be called before any of the view resolvers which will identify whether the requested resource us static and render accordingly. But this would be invoked for every htttp request which is not desirable.
Unfortunately I wasn't able to figure out how return a static resource in runtime with spring, but I resolved the situation using the old and good Filter.

Resources