spring boot not launching static web content - spring-boot

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/");
}
}

Related

Spring Boot and GlassFish

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/"})

Spring boot #Autowired is not working in the servlet duriing the server startup

I have servlet whose load on startup property is '1', in this servlet I have to cache database entries during the application server startup.
In this servlet I am calling the CacheService which retrieves the db objects, its annotated with #Autowired annoatation, during the application startup the CacheService object is null.I have annotated the CacheService with #Service annotation. The #Autowired annotation is not working.
#Service
public class CacheService {
#Autowired
private IJobsService jobsServiceImpl;
public List<Jobs> getALLJobs(){
List<Jobs> alljobs = jobsServiceImpl.findAllJobs();
return alljobs;
}
}
public class StartupServlet extends HttpServlet {
#Autowired
private CacheService cacheService; -- object is null not autowired
}
Below is the main class
#EnableCaching
#EnableJpaRepositories(basePackages = {"com.example.demo.repository"})
#EntityScan(basePackages = {"com.example.demo.entity"})
#SpringBootApplication
#ComponentScan(basePackages={"com.example.demo"})
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class})
public class DemoApplication extends SpringBootServletInitializer implements WebApplicationInitializer{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
#Bean
ServletRegistrationBean myServletRegistration () {
ServletRegistrationBean srb = new ServletRegistrationBean();
srb.setServlet(new StartupServlet());
srb.setUrlMappings(Arrays.asList("/path2/*"));
srb.setLoadOnStartup(1);
return srb;
}
}
Could some body help me on this...?
You should do some additional work for this. You have to talk to beanFactory-like spring component and ask it to make that particular instance an eligible bean. AutowireCapableBeanFactory should do the trick.
Here is a simple example based on code you have provided
#SpringBootApplication
public class So44734879Application {
public static void main(String[] args) {
SpringApplication.run(So44734879Application.class, args);
}
#Autowired
AutowireCapableBeanFactory beanFactory;
#Bean
ServletRegistrationBean myServletRegistration() {
ServletRegistrationBean srb = new ServletRegistrationBean();
final StartupServlet servlet = new StartupServlet();
beanFactory.autowireBean(servlet); // <--- The most important part
srb.setServlet(servlet);
srb.setUrlMappings(Arrays.asList("/path2/*"));
srb.setLoadOnStartup(1);
return srb;
}
#Bean
MyService myService() {
return new MyService();
}
public static class MyService {
String time() {
return "Time: " + System.currentTimeMillis();
}
}
public static class StartupServlet extends HttpServlet {
#Autowired
MyService myService;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final PrintWriter writer = resp.getWriter();
writer.write(myService.time());
writer.close();
}
}
}
=>
$ curl -XGET localhost:8080/path2
Time: 1498299772141%
You're creating the servlet by using new so you need to provide its dependencies. Since you're using a mix of annotation and java code configuration you can accomplish it like this:
public class StartupServlet extends HttpServlet {
private CacheService cacheService;
public StartupServlet(CacheService cacheService) {
this.cacheService = cacheService;
}
// ... rest of servlet
}
Main class:
#Bean
ServletRegistrationBean myServletRegistration (CacheService cacheService) { // <<<--- cacheService will be provided here by Spring because it's annotated
ServletRegistrationBean srb = new ServletRegistrationBean();
srb.setServlet(new StartupServlet(cacheService));
srb.setUrlMappings(Arrays.asList("/path2/*"));
srb.setLoadOnStartup(1);
return srb;
}

Spring Boot + JSF static page configurations

am getting started with Spring Boot + JSF.
Spring documentation says:
Spring will automatically load and serve resources inside
/static (or /public or /resources or /META-INF/resources.
This is not working for me.
it is discouraged to use the "webapp" (src/main/webapp) folder.
But for my static content, it seem to be the only folder thats working with my JSF static page.
see Spring Boot static content.
I have tried these configuration:
#Configuration
public class JSFServletConfigs implements ServletContextInitializer// ,ServletContextAware
{
#Override // ServletContext initiallization parameters
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("facelets.DEVELOPMENT", "false");
servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Development");
servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
servletContext.setInitParameter("javax.faces.PARTIAL_STATE_SAVING_METHOD", "true");
servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "-1");
}
#Bean // Registering the FacesServlet.
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet) {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
FacesInitializer facesInitializer = new FacesInitializer();
Set<Class<?>> clazz = new HashSet<Class<?>>();
clazz.add(JSFServletConfigs.class);
facesInitializer.onStartup(clazz, servletContext);
}
};
servletRegistrationBean.addUrlMappings("*.xhtml", "*.jsf", "*.html");
return servletRegistrationBean;
}
#Bean
public InternalResourceViewResolver jsfViewResolving(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/<sub-folder of any LOCATION>/");
viewResolver.setSuffix(".xhtml");
return viewResolver;
}
}
Servlet pre-configs:
#Configuration
#EnableWebMvc
public class DefaultServletConfigs extends WebMvcConfigurerAdapter {
#Override // Enabling the default Servlet at path="/"
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
private final String[] LOCATIONS = {"<All my possible locations>"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!registry.hasMappingForPattern("/**")){
registry.addResourceHandler("/**").addResourceLocations(LOCATIONS);
}
if(!registry.hasMappingForPattern("webjars")){
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
My Question are:
What am I missing here?
How do I get the flexibility to place my resources in any of the other folders above
(i.e. "/static", "/public", "/resources", "/META-INF/resources").

Hystrix turbine is not working

I am configuring hystrix turbine dashbord using ConfigPropertyBasedDiscovery . When I hit normal stream URL, it works fine
http://localhost:8080/turbine.stream?cluster=EXAMPLE
But when I try to load this cluster stream in dashbord it show below error "unnable to connect command matrix" on browser and on console "EventSource's response has a MIME type ("text/plain") that is not "text/event-stream". Aborting the connection.". Please have look on screen shot.
Below is my config.properties
turbine.aggregator.clusterConfig=EXAMPLE,EXAMPLE1
turbine.instanceUrlSuffix=:9080/hystrix.stream
turbine.ConfigPropertyBasedDiscovery.EXAMPLE.instances=localhost
turbine.ConfigPropertyBasedDiscovery.EXAMPLE1.instances=139.126.244.170
InstanceDiscovery.impl=com.netflix.turbine.discovery.ConfigPropertyBasedDiscovery
My Application.java
#EnableHystrixDashboard
public class Application extends SpringBootApplication {
private static Class<Application> applicationClass = Application.class;
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
TurbineInit.init();
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
super.configure(application);
return application.sources(applicationClass);
}
}
And servlet registration for "/turbine.stream"
#Configuration
public class ServletRegistrationConfig {
#Bean
public ServletRegistrationBean registerTurbineBean(){
return new ServletRegistrationBean(new TurbineStreamServlet(), "/turbine.stream");
}
}
Please assist me in this. And let me know if I missed out in configuration.

Change main endpoint in Spring Data Rest (usind Spring Boot)

Im building a small application using Spring (Boot, Data, Data Rest).
I have some JpaRepositories that aumotatically are exported as Rest endpoints.
What i want to do is to change the base path from / to /api.
Now to list all people for example i do a GET to http://localhost:8080/people and i want the url to be http://localhost:8080/api/people.
I tried adding this config class but nothing happened (it seems that Spring Boot overrides this config):
public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] { Application.class};
}
#Override
protected Class<?>[] getServletConfigClasses()
{
return new Class<?>[] { RestExporterRestConfig.class, RepositoryRestMvcConfiguration.class };
}
#Override
protected String[] getServletMappings()
{
return new String[] { "/api/*" };
}
}
My Application.java:
#Configuration
#ComponentScan
#Import(RestExporterRestConfig.class)
#EnableJpaRepositories
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and RestExporterRestConfig:
#Configuration
public class RestExporterRestConfig extends RepositoryRestMvcConfiguration {
#Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
#Override
protected void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
v.addValidator("beforeCreate", validator());
}
#Bean
#Qualifier
public DefaultFormattingConversionService defaultConversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addConverter(StringToDate.INSTANCE);
return conversionService;
}
#Bean
public DomainClassConverter<?> domainClassConverter() {
return new DomainClassConverter<DefaultFormattingConversionService>(defaultConversionService());
}
}
Well i figured it out. SpringWebAppInitializer is not necesary in this case. I just added this code to Application.java:
#Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean reg = new ServletRegistrationBean(dispatcherServlet);
reg.addUrlMappings("/api/*");
return reg;
}
I think this is the correct way to modify (add, change mappings, etc) servlets using Spring Boot.

Resources