unable to load static file in spring 4 - spring

Hi I am trying to load the jquery file in jsp but getting 404
Find below the project structure
I have configured the following in configuration too
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "common.spring.controller" })
public class WebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
}
below is how i include file in jsp
<script type="text/javascript" src="/resources/jsFiles/jquery-3.3.1.min.js"></script>
Dono why its not working.
UPDATE: I am able to see the resources folder under target/project snapshot/resources but getting 404 for url
http://localhost:8080/resources/jsfiles/jquery-3.3.1.min.js
directly hitting below Url didnt work either
http://localhost:8080/Sample/resources/jsfiles/jquery-3.3.1.min.js

Finally was able to resolve the issue
removing addResourceHandlers method and including the below code did the trick
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configure) {
configure.enable();
}
in jsp i used the include like below
<script type="text/javascript" src="resources/jsFiles/jquery-3.3.1.min.js"></script>

Related

Problems adding spring webflow to a spring boot and joinfaces application

I am trying to add webflow to a spring boot app using joinfaces library.
I am using primefaces-spring-boot-starter and jetty-spring-boot-starter to configure jetty server.
Added necessary webflow dependencies to pom and configured necessary flowregistry, flowbuilderservices, flowexecutor and flowhandlermapping, ...
The application start correctly, reads the flows definitions from xmls and if enter to a flow via url the decision states are running correctly, reads the corresponding view state .xhtml file, calls the managed bean methods, and all are working apparently well.
But... once finished executing bean methods, when I hope to html be rendered in browser, the application is redirected to app root folder without any error in the log.
I have this behavior with all the flows of the application. Bean methods are executed correctly and when I hope to see the html... redirected to root.
Anyone tried to add webflow to a joinfaces jsf application successfully? I am missing to override some default configuration of joinfaces?
Thanks.
public class MvcConfiguration implements WebMvcConfigurer {
#Autowired
private WebFlowConfiguration webFlowConfiguration;
#Bean
public FlowHandlerMapping flowHandlerMapping() {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1);
handlerMapping.setFlowRegistry(this.webFlowConfiguration.flowRegistry());
return handlerMapping;
}
#Bean
public FlowHandlerAdapter flowHandlerAdapter() {
JsfFlowHandlerAdapter adapter = new JsfFlowHandlerAdapter();
adapter.setFlowExecutor(this.webFlowConfiguration.flowExecutor());
return adapter;
}
#Bean
public ViewResolver faceletsViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(JsfView.class);
resolver.setPrefix("/");
resolver.setSuffix(".xhtml");
return resolver;
}
}
#Configuration
public class WebFlowConfiguration extends AbstractFacesFlowConfiguration {
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder()
.setBasePath("classpath*:/META-INF/resources/flows")
.addFlowLocationPattern("/**/*.xml")
.setFlowBuilderServices(flowBuilderServices())
.build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setDevelopmentMode(true)
.setViewFactoryCreator(new JsfViewFactoryCreator())
.build();
}
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry())
.addFlowExecutionListener(new FlowFacesContextLifecycleListener())
.addFlowExecutionListener(new SecurityFlowExecutionListener())
.setMaxFlowExecutionSnapshots(0)
.build();
}
}

how to specify welcome-file-list in WebApplicationInitializer.onStartup()

Currently I have a web application where we are using web.xml to configure the application. The web.xml has welcome-file-list.
<web-app>
...
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
We are planning to use spring framework and use java class for application configuration.
class MyApplication extends WebApplicationInitializer {
public void onStartUp(ServletContext context){
...
}
}
How do I specify welcome-file-list in this java class?
While developing Spring MVC application with pure Java Based Configuration, we can set the home page by making our application configuration class extending the WebMvcConfigurerAdapter class and override the addViewControllers method where we can set the default home page as described below.
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.myapp.controllers" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
It returns home.jsp view which can be served as home page. No need to create a custom controller logic to return the home page view.
The JavaDoc for addViewControllers method says -
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.
2nd way - For static HTML file home page we can use the code below in our configuration class. It will return index.html as a home page -
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
3rd way - The request mapping "/" below will also return home view which can be served as a home page for an app. But the above ways are recommended.
#Controller
public class UserController {
#RequestMapping(value = { "/" })
public String homePage() {
return "home";
}
}
You can't
As specified in Java Doc
public interface WebApplicationInitializer
Interface to be implemented
in Servlet 3.0+ environments in order to configure the ServletContext
programmatically -- as opposed to (or possibly in conjunction with)
the traditional web.xml-based approach.
but you still need minimal configuration in web.xml , such as for
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
#EnableWebMvc
#Configuration
#ComponentScan("com.springapp.mvc")
public class MvcConfig extends WebMvcConfigurerAdapter {
...
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/pages/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
...
}
This might help.
this works for me...
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}

Root Context path in spring application

I am running application using tomcat server, when server start i will get url
http://localhost:8080/TestApp/
and displaying index.jsp file but when i click link in index file it is displaying url like
http://localhost:8080/testsuccess
but it should display like
http://localhost:8080/TestApp/testsuccess
can any please help me to solve this.
SpringConfiguration.java
#Configuration
#EnableWebMvc
#ComponentScan("com.testapp")
#EnableTransactionManagement
public class SpringConfiguration {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringWebAppInitializer.java
public class SpringWebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(SpringConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
MyController.java
#Controller
public class MyFirstController
{
#RequestMapping(value = "/" , method = RequestMethod.GET)
public String testApp() throws Exception{
return "index";
}
#RequestMapping(value = "/testsuccess", method = RequestMethod.GET)
public String testAppSuccess() {
Map<String, Object> model = new HashMap<String, Object>();
return "success";
}
}
got it i should use
Next
it will give the context path.
I think your problem comes from the link inside your index.jsp. They might look like ... You should use either jstl or spring tag lib to handle links / urls in your pages. They both have the ability to prepend the deployment / context path of your application.
jstl example:
with taglib xmlns:c="http://java.sun.com/jsp/jstl/core" included you can create an anchor like ..
spring example:
with taglib xmlns:spring="http://www.springframework.org/tags" your link will be created in two steps:
<spring:url value="/testsuccess" var="myurl" htmlEscape="true"/>
...
Update: Wrong function name in jstl taglib version.

Mapping Controller URLs to JSP in WEB-INF

I am new to Spring and I would like to map some URLs to JSP pages. I am trying this for 2 hours now, but I can't get it working. I am sure this is very simple, but I am new to Spring. I am using Spring Boot.
(Yes, I found topics like How can I map my Spring URL to a JSP file in /WEB-INF/views?, but in my opinion I am doing everything right...)
This is my Controller. If I put a breakpoint there, it gets called. Therefore I think something is wrong with the ViewResolver...
#Controller
#RequestMapping("customers")
public class WebController {
#RequestMapping(method=RequestMethod.GET)
public String customers(Locale locale, Model model) {
return "customers";
}
}
This is my WebSecurityConfigurerAdapter (I am using Spring Security):
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//Some other methods, not relevant for this
#Bean
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
And my JSP-file is placed in WEB-INF/views/customers.jsp.
When I call localhost:8080/customers/ I get (this is the only error. No others in server log...):
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Aug 11 14:18:47 CEST 2014
There was an unexpected error (type=Not Found, status=404).
Thanks to Serge Ballesta I figured it out. :-)
I needed a configuration class which extends WebMvcConfigurerAdapter and is annotated with #EnableWebMvc. There I need to override the methods below. Annotating only WebSecurityConfigurerAdapter with #EnableWebMvc is not enough and results in "No mapping found for HTTP request with URI...."
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

META-INF/resources not works properly with #EnableWebMVC in Spring Boot

1.
I'm working with Spring Boot. My Main class very simple
#ComponentScan
#EnableAutoConfiguration
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#2. Now I would like to make my static content externalised into a jar file. So, below is the jar project
/pom.xml
/src/main/resources/META-INF/resources/hello.json // here is my resource
I do maven install and put the dependency into the main app, run the app normally. Now I can invoke http://localhost:8080/hello.json to get my hello.json file
#3. Then, the next step is using the Apache Tiles for my main web project, so I create a #EnableWebMvc class to configure the tilesViewResolver
#Configuration
#EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
public #Bean TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
public #Bean TilesConfigurer tilesConfigurer() {
TilesConfigurer ret = new TilesConfigurer();
ret.setDefinitions(new String[] { "classpath:tiles.xml" });
return ret;
}
}
Then I started again the application and try the hello.json to ensure everything still works properly. But, the 404 page appear. Delete the WebMvcConfiguration give back my hello.json.
What configuration I should do to resolve this issue?
Thanks a lot.
In Spring MVC, using XML configuration, you have to have a tag like the following to service static content:
<mvc:resources mapping="/js/**" location="/js/"/>
This insinuates that Spring Boot is doing something to automatically guess that you have static content and properly setup the above example in META-INF/resources. It's not really "magic", but rather that they have a default Java Configuration using #EnableWebMvc that has some pretty reliable default values.
When you provide your own #EnableWebMvc, my guess is you are over-writting their "default" one. In order to add back a resource handler, you would do something like this:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
This is equivalent to the XML above.

Resources