Serve static html files omitting the .html extension in the url - spring-boot

With the fine way to serve static html/css/js resources from src/main/resources/static, is there a way to have some form of url abstraction?
Precisely, I would like to remove the .html ending from the urls.

To return html static file without extension is the same as return view name from any of templates engines (jsp, theamleaf, freemarker), the thing here you do not need to run any templates processing on view file, you just return it as it is.
Add code below to your Spring configuration:
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("pages/");
internalResourceViewResolver.setSuffix(".html");
return internalResourceViewResolver;
}
Be careful /pages folder should be inside your ResourceLocation
, that means ResourceLocation + "/pages/" + pageName.html in browser should give you desired file (if you already configured servicing of static files it will not be a problem for you to find your ResourceLocation, check method addResourceHandlers in your WebMvcConfigurer)
Now at your WebMvcConfigurer you can add:
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/admin").setViewName("admin");
registry.addViewController("/contact").setViewName("contact");
registry.addViewController("/error").setViewName("index");
}
or just use it, as you would use it in usual view resolver within MVC controller
#GetMapping("/")
public String greeting() {
return "index";
}

A request mapping that ignores all URLs that have a file extension and adds .html to URLs with no file extension.
#Controller
...
#RequestMapping("/{page:^(?!.*[.].*$).*$}")
public String requestOther(#PathVariable("page") String page) {
return "/"+page+".html";
}
...
Change the "/" to a sub directory if needed e.g. "/pages/".

Related

Loading React Pages from Spring Controller

I have this code in my Spring Boot Application
#RestController
public class SampleController {
public SampleController() {
File file = new File("restresources");
System.out.println("File -> "+ file.getAbsolutePath());
}
#GetMapping(value = "/sample")
public String sampleText(HttpServletRequest request){
System.out.println("Sample Text");
return "Sample Text";
}
#RequestMapping()
public String acceptAny(){
return "ASDasdasdasdasd";
}
}
The acceptAny Method accepts any url hit from browser? But I have react files in my public folder too. So, when I hit localhost:8090/, instead of loading react index.html, it loads acceptAny() method.
How can I load react index.html instead of invoking this acceptAny() method or is there any method for loading React index.html from Controller itself?
Any help is highly appreciated!
first of all you have remove method acceptAny is hasn't any useful duties.
Than you should build your reactjs project and copy build files in resources/public or resources/static, than run project and open in browser localhost:8090/

How to bring in ASP.NET Core MVC to an existing ASP.NET blank project?

I have an ASP.NET Core blank project, and it works great to serve static files through https://localhost/filename. Now I want to add MVC functions to it. But referencing https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-controller?view=aspnetcore-2.2&tabs=visual-studio , after adding "Controllers" folder, add a controller class:
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
StartUp.cs is like:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseStaticFiles();
}
Builder is like:
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
after all this, I still can't access "https://localhost/HelloWorld/Welcome/".
What did I omit?
You have no default route specified, or routing of any sort for that matter. The quickest fix is to change app.UseMvc() to app.UseMvcWithDefaultRoute(). Alternatively, you can add attribute routes:
[Route("[controller]")]
public class HelloWorldController : Controller
{
[HttpGet("Welcome")]
public string Welcome()
{
return "This is the Welcome action method...";
}
}

jar package is not behaving as expected

I have made a code using spring boot and itextpdf 5, actually I am trying to do something like this example
https://github.com/aboullaite/SpringBoot-Excel-Csv
my code is working fine when I run it in my STS IDE, but it shows error as error resolving template when I create jar file and run it, can anyone please help
Edit:- I am using thymeleaf for html view
Code
this is my webconfig class
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true).ignoreAcceptHeader(true);
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolvers.add(excelViewResolver());
resolvers.add(pdfViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
#Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
/*
* Configure View resolver to provide Pdf output using iText library to
* generate pdf output for an object content
*/
#Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
}
}
and here are my controller methods
#GetMapping( "/download")
public String download(Model model) {
model.addAttribute("cards", new StudentsDto());
return "getReportCard";
}
#PostMapping("/download")
public String postReportCard(#ModelAttribute("cards") StudentsDto cards, Model model){
List<Students> sList=studentService.searchByClassSectionBySession(cards.getClassSection(), cards.getSession());
model.addAttribute("studentsList", sList);
return "";
}
My question is , If everythinbg is working fine on running code as spring boot application through my STS IDE then why the jar I have created is not showing pdf views ?
I have created jars from my sts ide, i did maven clean and then i created jar using maven install
Solved
Was a stupid mistake, I don't kn how but in my template folder I changed the name of file getReportCard.html as getReportCArd.html.
Was a silly mistake and I checked upon each and every possible configuration. :-)

Spring Boot displays images in some pages but not others

I'm facing issues with images in my Spring Boot + Thymeleaf application.
After reading a lot of fixes I'm able to show images in some of my app's pages but in other pages the images doesn't show.
I think that the number of paths in the request made is involved. It seems that requests to /myaction render pages showing images while requests to /myaction/other render pages not showing images.
In the fomer the successful request to obtain the images is:
http://localhost:8080/myapp/images/logo.png
In the latter the failed request to obtain the images is:
http://localhost:8080/myapp/myaction/images/logo.png
I append my configuration:
In my implementation of WebMvcConfigurerAdapter:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/"
};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
Controller class:
#Controller
#RequestMapping(path="/myaction")
public class PagosController {
#GetMapping(path="")
public String show(Model model) {
//...
}
#GetMapping(path="/other")
public String show2(Model model) {
//...
}
}
In my html template I load the image this way:
<img th:src="#{images/logo.png}" />
logo.png
The file logo.png is located in src/main/resources/static/images
I have no clue why this is happening. Any idea on why images are getting requested at http://localhost:8080/myapp/myaction/images/logo.png? Thanks in advance.
According to your configuration, the images are available from the root /.
So you should be able to use <img th:src="#{/images/logo.png}" /> in any page.

configuring Spring MVC welcome page

I was trying for two days to set up the index page using spring 4.
After many attempts I got a piece of code that worked
But I did not understand why it worked.
Could you tell me why.
public class MyWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
{
protected Class<?>[] getRootConfigClasses() {
return new Class[] {AplicationConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfiguration .class};
}
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
Here's the snippet of code I found
// #Bean
// public InternalResourceViewResolver internalResourceViewResolver() {
// InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// viewResolver.setPrefix("/WEB-INF/html/");
// viewResolver.setSuffix(".html");
// return viewResolver;
// }
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/html/");
super.addResourceHandlers(registry);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController( "/" ).setViewName( "forward:/index.html" );
// registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
// super.addViewControllers( registry );
}
my folders
1) why InternalResourceViewResolver do not work?
2) How does addResourceHandler and addViewController work? What are these paths?
3)And how do I add the css and javascripts file to the index page? like
<link href="/css/bootstrap.min.css" rel="stylesheet">
The page loads but this without the css and javascript files
I want to thank everyone who helped me because I'm a newbie in spring, thanks guys.
Only configuring InternalResourceViewResolver is not enough to serve static html. You also need to bind a path through controller to serve the page. As this is just a static page you can do that with
addViewControllers.
registry.addViewController("/").setViewName("index");
2.
addResourceHandlers: Add handlers to serve static resources such as images, js, and, css files from specific locations under web application root, the classpath, and others.
addViewControllers: Configure simple automated controllers pre-configured with the response status code and/or a view to render the response body. This is useful in cases where there is no need for custom controller logic -- e.g. render a home page, perform simple site URL redirects, return a 404 status with HTML content, a 204 with no content, and more.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.html#addResourceHandlers-org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry-
3.
To make the resources(js, css, img) available, you need to add following configuration inside your addResourceHandlers methods.
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
And then to include css or js in a JSP page, you can use JSTL tag c:url or Spring tag spring:url.
<link href="<c:url value="/css/styles.css" />" rel="stylesheet">
<spring:url value="/css/styles.css" var="mainCss" />
<link href="${mainCss}" rel="stylesheet" />

Resources