I'm new a spring-boot and spring framework. According to me, web app create and deploy very easy with spring-boot but when i run my sample spring web app, application not found "welcome.html" page. I checked all similar question on stackoverflow and not worked me. I cannot see little issue but I didnt find my problem. My application structure and codes are below:
MyApplication class is below:
#SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
WelcomeController class is below:
#Controller
public class WelcomeController {
#RequestMapping(value = "/welcome")
public String welcome() {
return "welcome"; //<- this is your login.html if it is directly in resource/templates folder
}
}
application.properties file is below:
spring.mvc.view.prefix = templates/
spring.mvc.view.suffix = .html
spring.mvc.static-path-pattern=/resources/**
WebMvcAppConfig class is below:
public class WebMvcAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry); //To change body of generated methods, choose Tools | Templates.
registry.addViewController("/welcome").setViewName("welcome.html");
}
}
Firstly thanks a lot for quickly response my question #Andy Wilkinson and georges van. I looked for in spring boot reference guide and Serving Web Content with Spring MVC and I learned a lot of information about spring-boot. I removed WebMvcAppConfig because this class not necessary for starter and removed SpringBootServletInitializer. I moved html files into templates as you say. I keep simple and application run without issues.
I'm using Spring Rest controller for my Restful calls. I'm having Spring 4.3.x version of JAR's. When I run the project itself, the index.jsp is not getting called. I've not configured anything in xml because I'm using annotation method. Here are my files.
P.S : I'm not using Maven, its a dynamic web project and all Spring JAR's (Webmvc, web, core, context, beans) are added to build path.
I've followed http://viralpatel.net/blogs/spring-4-mvc-rest-example-json/
AppConfig
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "net.ifg.spring")
public class AppConfig {
}
AppInitializer
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
CustomerDAO
public class CustomerDAO {
// Dummy database. Initialize with some dummy values.
private static List<Customer> customers;
{
customers = new ArrayList();
// Add customers here
}
public List list() {
return customers;
}
}
CustomerRestController
#RestController
public class CustomerRestController {
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/customers")
public List getCustomers() {
return customerDAO.list();
}
}
Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>IFG</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Why its not able to hit the URL http://localhost:8080/IFG/customers? There should be the issue with AppInitializer file.
Any ideas would be greatly appreciated.
You have to specify IFG in a request mapping. The current link according to your mapping should be http://localhost:8080/customers. Add the #RequestMapping annotation specifying the path.
#RestController
#RequestMapping("/IFG")
public class CustomerRestController
#RestController
#RequestMapping("/IFG")
public class CustomerRestController {
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/customers")
public List getCustomers() {
return customerDAO.list();
}
}
Now hit the url like below :
localhost:port/IFG/customers
To make it work, you should add:
#RestController
#RequestMapping("/IFG")
and check the number of port: 8080 (it could be 9080 or whatever)
Just try access http://localhost:8080/customers (without /IFG), just copied that project locally, on my tomcat, and it works, without running mvn tomcat7:run.
Your setup in web.xml <display-name>IFG</display-name> is not the application context path by which to access.
From the docs:
display-name
The optional display-name element specifies the Web
application display name, a short name that can be displayed by GUI
tools.
After http://localhost:8080 you have to give your app name prior calling the controller. Lets say your app name is myApp, so the url should be:
http://localhost:8080/myApp/customers
provided you use the controller in your question, if you have added to your controller #RequestMapping("/IFG") as per other answers suggested then you have to change the url to:
http://localhost:8080/myApp/IFG/customers
EDIT
I see in your AppInitializer class you are returning null from getServletConfigClasses(). I believe that the AppConfig.class should be returned there.
#Override
protected Class[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
Just checked that it was due to javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class. This I've fixed by adding commons-logging-1.2.jar, spring-aop, spring-expression jars. Atleast I'm able to point to the right method.
I'm trying to implement simple web service using Spring 4. But my userService doesn't seem to work.
I have configuration like this:
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ PersistenceConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{
};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/api/*"};
}
}
With Persistence config for my in-memory HSQLDB like this:
#Configuration
#ComponentScan("example.userService")
#PropertySource("classpath:hibernate.properties")
#EnableJpaRepositories("example.userService.repo")
public class PersistenceConfig {
#Autowired
Environment env;
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
/* ... */
return entityManagerFactoryBean;
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:db/data.sql")
.build();
}
}
I have an entity User. And here is my repository:
#Repository
#RepositoryRestResource
public interface UserRepo extends CrudRepository<User, Long> {
List<User> findAll();
List<User> findByFirstName(#Param("firstName") String firstName);
}
And I also have na embedded jetty on port 9999 to run this service.
And when jetty starts and i go to localhost:9999/api/users/ or /user/1 or smth like that, an error 404 occurs. findByFirstName method also does not work.
I think this happens because Servlet Dispatcher doesn't know about my exposed repository. But I also don't know how to 'register' it since I don't want to use controller for it.
I have read spring docs here, here and another tutorials but most of them do not provide any configs and describe repositories that simply just work.
Any suggestions on what can I do with it and what can cause this problem since nothing is shown in console and in compile-time everything work fine?
Thanks in advance!
UPD 1:
I've added #RepositoryRestResource to UesrRepo according to Accessing JPA Data with REST but /api/users is still 404.
UPD 2:
I've simplified question by removing service-part of it since it requires controller according to #Antoniossss's comment. Not it's just that simple: Which configuration (if any) should I use to expose repository?
It looks like you missed Spring data rest configuration and have only MVC configuration. You need to add bean RepositoryRestConfigurer to your configuration or extend RepositoryRestConfigurerAdapter.
I have a Spring Boot app using SpringWS. Inside of the WsConfigurerAdapter I am overriding addInterceptors in order to add logging/authentication/validation/etc.
#Configuration
#EnableCaching
#EnableWs
public class WebServiceConfig extends WsConfigurerAdapter {
...
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
EnvironmentSettings environment = getEnvironmentSettings();
interceptors.add(getLogSetupInterceptor());
interceptors.add(getAuthenticationInterceptor());
interceptors.add(getServerLoggingInterceptor());
interceptors.add(getAuthorizationInterceptor());
ServerPayloadValidatingInterceptor validatingInterceptor = new ServerPayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(environment.isValidateSoapRequest());
validatingInterceptor.setValidateResponse(environment.isValidateSoapResponse());
validatingInterceptor.setXsdSchema( xsdSchema());
interceptors.add(validatingInterceptor);
}
}
What is strange is that when run locally, all of these interceptors are being added and run for every request just fine. However, when I deploy the application as a .war to WAS, this one method is not being run. I even added logging statements and I can tell that it's this method that's getting skipped over instead of the interceptors themselves. Does anybody know something about spring boot .war files that I don't?
Also, here is my Application class:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I figured out what I did wrong. It turns out I was creating a servlet mapping in both my WebServiceConfig and my web.xml both at /*.
I created to simple spring mvc configuration using java based configuration:
Config file:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.kitchen")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/kitchen/**").addResourceLocations("/kitchen/");
registry.addResourceHandler("/images/**").addResourceLocations("file:E:/Work/images/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Initializer:
public class WebMvcAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[0];
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfiguration.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{new CORSFilter()};
}
}
Controller:
#Controller
public class IndexController {
#RequestMapping(value = "/")
public String getIndexPage() {
return "kitchen/index.html";
}
}
All files are located in same package. But when I try to deploy in tomcat, nothing is deployed. I am not good in configurations so I would like to ask maybe I forgot something more? I do not want to use web.xml, just plain java configuration.
Also there could be problem creating modules and artifacts in in Idea IDE I moved not a lot of time ogo to it from eclipse. so here is everithing a little bit different. Here are my configurations of project modules and artifacts, can you please tell me what could be problems in my situation?
Screens: