Static resources are not being served - spring-mvc

I want to serve static resources in my spring web MVC application. In this project, I am using annotation based configuration, but static resources are not getting served. I tried from both side:
1st way
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
2nd way
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

If you use SpringBoot default configuration you can access static resource from default web route. For example http://yourhost:8080/images/test.jpg where images is a a folder in the static branch.

Related

Problem with my mvc app isnt using style.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.

Integrate vertex with existing spring web application

I have an existing Spring based web application. I want to integrate vertx within the application.
Is there a way to do so?
Yes, have a look at the Vert.x with Spring section in the examples repository on GitHub.
In spring boot it is fairly simple
#SpringBootApplication
#ComponentScan(basePackages = { "com.mypackage", "com.myotherpackage" })
public class MyApplication {
#Autowired
private MainVerticle mainVertical;
public static void main(String[] args) throws Exception {
new SpringApplication(MyApplication.class).run(args);
}
#PostConstruct
public void deployServerVerticle() {
Vertx.vertx().deployVerticle(mainVertical);
}
}
The #PostConstuct allows you to deploy all the verticals you want (all the properties are set at this point).
And it goes without saying that the MainVerticle should be marked with the #Component annotation.

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

Initializing ASP.NET Web application on application pool start

I have searched the web for over one day but I did not find anything I need.
I am developing an IIS web application with HttpHandlers and HttpModules. I need to initialize the application on first run (applying configuration). But I do not want to use global.asax.cs because I do not want implementations having a global.asax file in their folder (a web.config at most).
How do I run some code when the application pool is being initialized?
You could use the assembly level attribute PreApplicationStartMethodAttribute to have your startup code run early in the ASP.NET pipeline.
namespace MyWebService
{
public class MyHttpHandler: IHttpHandler, IDisposable
{
public static void StartUp()
{
//Application Startup Code;
}
public void ProcessRequest(HttpContext context)
{
//Do Something
}
public bool IsReusable { get; private set; }
public void Dispose(){};
}
}
}
}
And add the attribute to your AssemblyInfo.cs
[assembly: PreApplicationStartMethod(typeof(MyWebService.MyHttpHandler), "StartUp")]
For more info on PreApplicationStartMethod : https://msdn.microsoft.com/en-us/library/system.web.preapplicationstartmethodattribute

Serve static file index.html by default

I've got a very simple angular app project that needs to do nothing more than serve static files from wwwroot. Here is my Startup.cs:
public class Startup
{
public void ConfigureServices(IServiceCollection services) { }
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Whenever I launch the project with IIS Express or web I always have to navigate to /index.html. How do I make it so that I can just visit the root (/) and still get index.html?
You want to server default files and static files:
public void Configure(IApplicationBuilder application)
{
...
// Enable serving of static files from the wwwroot folder.
application.UseStaticFiles();
// Serve the default file, if present.
application.UseDefaultFiles();
...
}
Alternatively, you can use the UseFileServer method which does the same thing using a single line, rather than two.
public void Configure(IApplicationBuilder application)
{
...
application.UseFileServer();
...
}
See the documentation for more information.
Simply change app.UseStaticFiles(); to app.UseFileServer();
public class Startup
{
public void ConfigureServices(IServiceCollection services) { }
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseFileServer();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

Resources