Spring Boot and GlassFish - spring-boot

I actually have a spring boot application that i deployed on glassfish server 5.0 .
The probleme is that the jsp pages are not showing when i type the link.
I correctly configured the main class:
#SpringBootApplication
public class CaisseApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(CaisseApplication.class, args);
}
}
the controller looks like this:
#Controller
#RequestMapping("/imports_caisses_et_grandsLivres/")public class controller {
#RequestMapping(value = "")
public String index(Map<Object, Object> model) {
return "index";
}
}
The jsp pages are correctly created, and to acces them, i'm using application.properties:
spring.mvc.view.prefix= /WEB-INF/views/
spring.mvc.view.suffix= .jsp

Sorry, the brackets {} was missing in:
#Controller
#RequestMapping({"/imports_caisses_et_grandsLivres/"})

Related

Spring boot controller not being detected

Good day. I'm having issues with my Springboot app. The controller isn't being detected.The Component scan is used but it won't detect the controllers.
Folder structure
Application
#EntityScan(basePackages = "com.jokedata.models")
#EnableJpaRepositories(basePackages = "com.jokedata.repositories")
//#ComponentScan(basePackages = {"com.jokeweb.project.controllers"})
#SpringBootApplication(scanBasePackages = "com.jokeweb.project.controllers")
public class JokeApplication {
public static void main(String[] args) {
SpringApplication.run(JokeDataApplication.class, args);
}
}
Controller
#RestController
public class UserController {
#GetMapping("/home")
public String home() {
return "home";
}
}
Check if request URL or application port is correct or not.

#RestController returning blank

I'm building my first Spring Boot application. But I can't get my requestMapping controller answer properly.
This is my main class:
package com.hello.world;
#SpringBootApplication
public class HelloWorld implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(HelloWorld.class, args);
}
#Override
public void run(String... args) throws Exception {
....
}
}
And this is my RestController:
package com.hello.world.controllers;
#RestController
public class UrlMappingControllers {
#RequestMapping("/hi")
String home() {
return "Hello World!";
}
}
If I take a look at the log I can see the "/hi" mapping:
restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hi]}" onto java.lang.String com.hello.world.controllers.UrlMappingControllers.home()
But when I access: http:localhost:8080/hi I get a blank page, I expected seing the "Hello World" text.
Why am I getting a blank page?
--- Edit ----
I've just realised that I am getting the blank page only when I add a cxf service. I think it is because the #configuration annotation on this class:
package com.hello.world.helloWorld.configuration;
#Configuration
public class CXFConfiguration {
#Bean
public ServletRegistrationBean dispatcherServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}
#Bean(name=Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
SpringBus springBus = new SpringBus();
return springBus;
}
#Bean
public Endpoint endpointGreentingService() {
EndpointImpl endpoint = new EndpointImpl(springBus(), new GreetingServiceImpl());
endpoint.getFeatures().add(new LoggingFeature());
endpoint.publish("/GreetingService");
return endpoint;
}
}
Could it be related?
#RestController = #Controller + #ResponseBody which means that when you call your api at http:localhost:8080/hi the body of the response will contain the result of the home() handler, i-e "Hello world".
#RestControllerbehind the scene makes Spring MVC uses a Json Message Converter (by default) and all handler methods inside a class annoted with #RestController will return a JSON, that is why you do not see your text on your browser.
You can use Postman or ARC to test your app. Some web browsers like Firefox shows JSON directly.

Adding patterns to addResourceHandler always returned error when want to serve static content

I went through all question here, all docs according to Spring and couldn't find solution which make my case work.
The case is that I would like to secure my application (Spring Boot with Angular 4) by Spring Security. So the first things which I did was to add two Configuration classes, ex:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.anyRequest().permitAll().and().httpBasic();
}
#Configuration
#EnableWebMvc
#ComponentScan("com.inventory")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/", "/#/", "/resources/static/**")
.addResourceLocations("/resources/static/index.html", "/resources/static/index.html", "/resources/static/index.html");
}
}
#Controller
public class ViewController {
#RequestMapping(value = "/#/")
public String index() {
return "forward:/resources/static/index.html";
}
#RequestMapping(value = "/")
public String home() {
return "index.html";
}
}
As you see in Controller I tried to use to diffrent attempts to serve static content. Unfortunately all this returns:
There was an unexpected error (type=Internal Server Error, status=500).
Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'
What am I doing wrong? Why I can't get this static content? Of course my static content is under resources/static and there are .js files and ex. index.html.

Spring boot single page application - forward every request to index.html

I have a Spring Boot (v1.3.6) single page application (angular2) and i want to forward all request to the index.html.
A request to http://localhost:8080/index.html is working (200 and i get the index.html) but http://localhost:8080/home is not (404).
Runner.class
#SpringBootApplication
#ComponentScan({"packagea.packageb"})
#EnableAutoConfiguration
public class Runner {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext run = SpringApplication.run(Runner.class, args);
}
}
WebAppConfig.class
#Configuration
#EnableScheduling
#EnableAsync
public class WebAppConfig extends WebMvcConfigurationSupport {
private static final int CACHE_PERIOD_ONE_YEAR = 31536000;
private static final int CACHE_PERIOD_NO_CACHE = 0;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.setOrder(-1);
registry.addResourceHandler("/styles.css").addResourceLocations("/styles.css").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
registry.addResourceHandler("/app/third-party/**").addResourceLocations("/node_modules/").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(CACHE_PERIOD_NO_CACHE);
registry.addResourceHandler("/systemjs.config.js").addResourceLocations("/systemjs.config.js").setCachePeriod(CACHE_PERIOD_NO_CACHE);
registry.addResourceHandler("/**").addResourceLocations("/index.html").setCachePeriod(CACHE_PERIOD_NO_CACHE);
}
}
styles.css, /app/third-party/xyz/xyz.js,.. are working (200 and i get the correct file). Only /** to index.html is not working.
You can also add a forwarding controller like:
#Controller
public class ForwardingController {
#RequestMapping("/{path:[^\\.]+}/**")
public String forward() {
return "forward:/";
}
}
The first part {path:[^\\.]+} matches one or more of any character other than .. This makes sure request for a file.ext doesn't get handled by this RequestMapping. If you need to support sub-paths to also be forwarded, put /** outside of the {...}.
This one didn't work for me:
return "forward:/";
Thanks to Spring MVC #RestController and redirect I found a nicely working solution:
#RequestMapping(value = "/{[path:[^\\.]*}")
public void redirect(HttpServletResponse response) throws IOException {
response.sendRedirect("/");
}
Without looking at logs I'm not entirely sure why its not being mapped correctly, however if you want to map URLs to a view (HTML) then you will probably be better off using the viewController mechanism spring provides http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-config-view-controller. e.g.
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
(taken from spring docs linked above - this is how you should map a url to a view rather than re-purposing the mapping for static resources.)
I'm not sure if there is any kind of suffix filtering for the resource mapping - e.g. I don't know how spring decides to map requests to the ResourceHttpRequestHandler - have you tried (just to confirm or deny) whether something like http://localhost:8080/home.html amps to anything?
It's also possible that the html mapping you have defined above is just being ignored and the index.html is just working because of Spring-Boot's default home page behaviour: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java#L108
I had the same problem and the following worked for me. My html files are inside src/main/resources/static/app
The key was to remove #EnableWebMvc and add "classpath:/static/app/" to addResourceLocations! Hope this helps.
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/","classpath:/static/app/", "classpath:/public/" };
#Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
// forward requests to /admin and /user to their index.html
registry.addViewController("/portal").setViewName(
"forward:/app/index.html");
}
};
}

spring boot not launching static web content

Am trying to launch index.html in my spring boot app but see 404. What dependency am I missing?
build.gradle (multi project)
project('sub-project')
{
apply plugin: 'spring-boot'
compile (
"org.springframework.boot:spring-boot-starter-web:1.0.0.RC5",
"org.springframework.boot:spring-boot-starter-actuator:1.0.0.RC5"
.. few more app specific dependencies
)
project structure:
MainProject
-- sub-project
src
main
resources
index.html
Application class:
#Configuration
#EnableAutoConfiguration
class Application {
public static void main(String[] args) {
SpringApplication.run([SpringServlet, Application, "classpath:/META-INF/com/my/package/bootstrap.xml"] as Object[], args)
}
}
**Launching http://localhost:8080/index.html throws 404.**
Found the root cause. Changing the SpringServlet's Url mappings to "Rest" resources specific path fixed it.
Earlier "/*" was also interpreted by SpringServlet and was not able to render the index.html.
class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run([Application, "classpath:/META-INF/com/my/package/mgmt/bootstrap.xml"] as Object[], args)
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application);
}
#Bean
ServletRegistrationBean jerseyServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new SpringServlet(), "/rest/*");
Map<String, String> params = ["com.sun.jersey.config.property.packages": "com.my.package.mgmt.impl;com.wordnik.swagger.jersey.listing"]
registration.setInitParameters(params)
return registration;
}
#Bean
ServletRegistrationBean jerseyJaxrsConfig() {
ServletRegistrationBean registration = new ServletRegistrationBean(new DefaultJaxrsConfig(), "/api/*");
Map<String, String> params = ["swagger.api.basepath": "http://localhost:8080/api", "api.version": "0.1.0"]
registration.setInitParameters(params)
return registration;
}
#Configuration
public class WebConfig implements WebMvcConfigurer {
/** do not interpret .123 extension as a lotus spreadsheet */
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
configurer.favorPathExtension(false);
}
/**
./resources/public is not working without this
*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/public/");
}
}

Resources