access static html page from jar file using spring - java

I want to call home.html file present in jar under /WEB-INF/lib using spring.
Below is configuration class
#Configuration
#ComponentScan("com.barclays.mobile.gateway.controller")
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".html");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/component/**").addResourceLocations("classpath:/app/component/*");
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/app/assets/*");
registry.addResourceHandler("/home/**").addResourceLocations("classpath:/app/*");
}
}
Below is controller:
#Controller
public class StaffController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home() {
return "home";
}
}
Please suggest how to do this.?

remove / from /home, I guess that is the problem

Related

SpringBoot White page

I just start learning SpringBoot.
I use spring boot build-in tomcat get my spring boot program run. But when I try to visit the page, it gives me a Whitelabel Error Page.
When I start this program, it shows as follow:
I think my program and tomcat start successfully.
This is my start code:
DemoApplication.java
#SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
This is my Controller code:
BookController.java
#Controller
public class BookController {
private IBookService bookService;
public BookController(IBookService bookService) {
this.bookService = bookService;
}
#RequestMapping(value = "/book_list", method = RequestMethod.GET)
public String getAllBook(Model model, HttpSession httpSession, HttpRequest httpRequest) throws Exception {
List<Book> list = bookService.getAllBook();
model.addAttribute("bookList", list);
return "book";
}
}
So if I visit 'localhost:8080/bookstore/book_list', it will find the controller and this controller should help me go to the /WEB-INF/jsp/book.jsp because my WebMvcConfig like following:
WebMvcConfig.java
#Configuration
public class WebMvcConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
But why this is a white page?
This is my program structure:
DemoApplication is in a demo subpackage. The default is that it only scans subpackages of the class annotated with #SpringBootApplication, so it doesn't find any of your components.
Two ways to fix:
Move the class out of the demo package.
This is what Spring Boot demo applications usually do.
Specify the packages to scan:
#SpringBootApplication(scanBasePackages = "com.zx")
Alternatively, use #ComponentScan, same thing:
#SpringBootApplication
#ComponentScan("com.zx")

Unable to resolve static resources in Spring MVC

I know this question has a lot of answers but i cannot solve mine so that is why i decided to put up the question
I want to resolve both jsp and html files. Below is my spring resolver configuration
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("");
return resolver;
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/views/static");
}
and controller class is below:
#RequestMapping("/testApi2")
#Controller
public class TestController2
{
#RequestMapping("/showHomePage")
public ModelAndView showHome(){
return new ModelAndView("/static/about.html");
}
}
I have also attached screen shot of my directory structure, it is giving 404 on every request
I think that you should add to your web resolver config class one very special handling configurer:
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
This method enables static resources processing.
After some efforts , thanks to lot of documentation on Spring , i was able to resolve the issue
I found a solution(searched on net) with which we can use both JSP and HTML as views
Forget the question , below are the new settings
Static resources (.css,.js,.jpg) are placed in webapp/assets/
HTML files are in /WEB-INF/static/
Here is my configuration file :
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**") //
.addResourceLocations("/assets/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Please note i have used resolver.setSuffix("") both HTML and JSP
HTML code :
<link rel="stylesheet" href="/taxi/assets/css/theme-pink.css" />
Here taxi is the context root , means name of the project
Now if i run the below URL , it will fetch the image or CSS of js
localhost:8080/taxi/assets/css/icons.css

Controller doesn't work with spring

I use spring mvc with spring configuration (without xml). And it seems like IDEA doesn't go to controller code. Maybe somewhere path is incorrect so #RequestMapping doesn't work. But i can't understand where exactly.
Here is my Controller
#Controller
public class MainController {
#RequestMapping(value = "/" , method = RequestMethod.GET)
public String home() {
return "index";
}
#RequestMapping(value = "welcome", method = RequestMethod.GET)
public String welcome(Model m){
m.addAttribute("name","lol kkeke");
return "index2";
}
}
WebMvcConfig
#Configuration
#ComponentScan("com.chat")
#EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/");
registry.addResourceHandler("/styles/**").addResourceLocations("/styles/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/");
registry.addResourceHandler("/pages/**").addResourceLocations("/views/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index.jsp");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
So.. I solved a problem. It was in Controller - path. My Idea automatically change path from com.chat.controller to c.c.controller. So i rebuild project structure to com.chat.controller.Controller.class; and com.chat.config.Configuration.class.
Also, i found the next article about similar trouble. May be it will help somebody! How do I map Spring MVC controller to a uri with and without trailing slash?

What is the best way to configure PropertySourcesPlaceholderConfigurer / resource folders?

I have a (gradle/java/eclipse) project with what seems to me to be quite a standard folder structure
...main
java
...controller
...service
resources
webapp
...resources
WEB-INF
I'm having an issue I just don't understand although I have worked around it in a very messy way. If I specify the controllers folder in the component scan of my WebMvcConfigurerAdapter then the services classes can't pick up properties using the configured PropertySourcesPlaceholderConfigurer bean. If I broaden the component scan out the jsp files don't pick up the css includes!
So with this config class all is well but the properties aren't resolved int he service implementation class
config class
#EnableWebMvc
#Configuration
#ComponentScan({ "comm.app.controller" })
#PropertySource({ "classpath:app.properties" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
//used to handle html put and delete rest calls
#Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Service implementation class begins
#Service("appService")
#PropertySource({ "classpath:app.properties" })
public class appServiceImpl implements appService {
private RestTemplate restTemplate = new RestTemplate();
#Value("${property.reference}")
private String propref;
...
In this case ${property.reference} is not picked up but the view page styling (picked up from ...webapp\resources... .css) is fine.
If I change
#ComponentScan({ "comm.app.controller" })
to
#ComponentScan({ "comm.app" })
The properties are picked up (presumably because the propertyConfig bean comes into scope ?) but the local styling files can't be found ? Any link references to files webapp\resources... .css fails.
In the end I came to a bad (!?) solution of
1) keeping the scope of #ComponentScan({ "comm.app.controller" })
2) hacking the serviceimplementation class as so...
#Configuration
#Service("appService")
#PropertySource({ "classpath:app.properties" })
public class appServiceImpl implements appService {
private RestTemplate restTemplate = new RestTemplate();
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
#Value("${property.reference}")
private String propref;
...
Can anyone tell me if I've configured the path the the resources file incorrectly or maybe should be doing something differently with the propertyConfig bean ? (maybe injecting it or declaring another one in a different configuration file ?)

Spring MVC - Return static page

I'm struggling with trying to return a static web page from a spring MVC controller.
I followed this tutorial: http://www.tutorialspoint.com/spring/spring_static_pages_example.htm and yet it still isn't working.
This is how I defined the configuration (used configuration class):
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan({ "com.my.web.api"})
#ImportResource("classpath:db-context.xml")
public class ApiServletConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/resources/");
internalResourceViewResolver.setSuffix("*.html");
return internalResourceViewResolver;
}
}
The controller method:
#RequestMapping(value = "/{id}/view", method = RequestMethod.GET, produces = "text/html")
#ResponseBody
public String getPostByIdHtml( #PathVariable String id) throws IOException {
return "/resources/Post.html";
}
Under the webapp folder there's a folder named "resources" and under which there's a file "Post.html". What else should I do in order to get this page returned as HTML instead of getting the string "resources/Post.html"?
Thanks for the help.
Please remove the annotation #ResponseBody. Your browser should be redirected to the desired page once the annotation is removed.
This annotation indicates that the value returned by a method in your controller should be bound to the web response body. In your case, you do not need that: you need Spring to render page /resources/Post.html, so no need for this annotation.

Categories