Getting Error 404 from tomcat on intellij - java

I am trying to run tomcat in intellij, everything runs ok in the IDEA but when I try to open the corresponding page in the browser I get
HTTP Status 404 – Not Found with the Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. I've looked everywhere and did not find an answer, I hope you can help.
My code is as follows:
#EnableWebMvc
#Configuration
#ComponentScan({"com.asign.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver resolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
}
#Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;//new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
#Controller
public class AppController {
#RequestMapping(value = "/")
public String helloWorld(Model model) {
//let’s pass some variables to the view script
model.addAttribute("wisdom", "Goodbye XML");
return "hey"; // renders /WEB-INF/views/hey.jsp
}
}
I hope this is enough to help me with my problem. Thank you !
edit: I do get the following messages in the Localhost log:
INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
For anyone facing the same problem: I could not make this project work, but I used the one from
http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example-annotation/
and it worked just fine in my Intellij (after I removed the plugins from pom.xml)

Try to update your InternalResourceViewResolver's prefix to your views folder:
resolver.setPrefix("/WEB-INF/views/");
And you need to have hey.jsp in that views folder.

Related

Why does #ComponentScan behave differently for different configuration files?

I'm relatively new to Spring, and was following some examples.
During one of the examples I noticed that Spring wasn't mapping URI to methods.
I discovered that I put my #ComponentScan annotation on the wrong configuration class and fixed my problem.
So my question is why #ComponentScan works for one of these classes and not with the other?
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"org.zerock.controller"}) // This Works.
public class ServletConfig implements WebMvcConfigurer {
#Bean
public MultipartResolver multipartResolver(){
return new StandardServletMultipartResolver();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
registry.viewResolver(resolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
#Configuration
//#ComponentScan(basePackages = {"org.zerock.controller"}) This Doesn't Work
public class RootConfig {
}
// How the two configuration classes are initialized
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{ServletConfig.class};
}
I've read that root config classes and servlet classes are set up differently in the application context hierarchy.
I suspect that has something to do with this, but I fail to see how that would cause this.
Javadoc for AbstractAnnotationConfigDispatcherServletInitializer recommend to implement:
getRootConfigClasses() -- for "root" application context (non-web infrastructure) configuration.
getServletConfigClasses() -- for DispatcherServlet application context (Spring MVC infrastructure) configuration.
If an application context hierarchy is not required, applications may return all configuration via getRootConfigClasses()
So a #ComponentScan on the RootConfig should work if there are no duplication on the ServletConfig level.
Could you post the error you get and all classes?
I recommend you to place the RootConfig in the root of you packages and use #ComponentScan without specifying base package.

spring mvc no xml configuration 404 error

I am trying to develop a simple Spring MVC with no XML application .its basically show a simple home page. I am using tomcat on JetBrains IDE for development and problem is that when I run it on tomcat I see 404 error this is url http://localhost:8080/MySpringSecurityApp_war/
this is a controller
#Component
public class DemoController {
#GetMapping("/")
public String showHome(){
return "home";
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.luv2code.springsecurity.demo")
public class DemoAppConfig {
//define a bean for view resolver
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {DemoAppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
this is error log
9-Jun-2020 13:32:07.511 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/MySpringSecurityApp_war/] in DispatcherServlet with name 'dispatcher'
09-Jun-2020 13:32:07.604 WARNING [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/MySpringSecurityApp_war/] in DispatcherServlet with name 'dispatcher'
this is also how my project structure
You need to define a resource path if you adding something into your URL (after host part basically in your case MySpringSecurityApp_war) you are calling localhost:8080/MySpringSecurityApp_war/ but you didn't define the resource path anywhere so I guess what you need to do is either add #RequestMapping("/MySpringSecurityApp_war/") at class level or just call localhost:8080/ without any resource path
You can also use #RestController in place of #Component.
I hope it will work.

Spring Boot "No message available" error(status = 404),

I'm using Spring Boot with embeded Tomcat.
When it starts it logs into console:
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/home]}" onto public java.lang.String com.vlad.pet.contactlist.webapp.controller.SampleController.helloWorld(org.springframework.ui.Model)
So I guess the URL is mapped to the controller.
But http://localhost:8090/home gives me an error 404.
There was an unexpected error (type=Not Found, status=404).
No message available
Application.java
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
//overrides the configure() method to point to itself, so Spring can find the main configuration.
#Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ViewResolver getViewResolver() {
final TilesViewResolver resolver = new TilesViewResolver();
resolver.setViewClass(TilesView.class);
return resolver;
}
#Bean
public TilesConfigurer getTilesConfigurer() {
final TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions("WEB-INF/tiles/tiles.xml");
configurer.setCheckRefresh(true);
return configurer;
}
}
SampleController.java
#Controller
public class SampleController {
#RequestMapping (value = "/home")
public String helloWorld(Model model) {
model.addAttribute("pageTitle", "home");
return "base";
}
}
tiles.xml
<tiles-definitions>
<definition name="base" template="/WEB-INF/tiles/basic/basic-template.jsp">
<put-attribute name="head" value="/WEB-INF/tiles/basic/head.jsp" />
</definition>
</tiles-definitions>
My project structure
You can use #RestController instead of #Controller.
#RestController
public class SampleController {
...
You're returning 'home' from your controller method, but I don't see a home.jsp on your project structure.
I solved this problem by enabling default servlet:
#Configuration
#EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Source: Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error
In my case, my eclipse project was showing an error. i had to do mvn install from eclipse, update maven dependencies and then start the server from eclipse.

Troubles running spring mvc java based configuration in idea local tomcat

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:

getServletConfigClasses() vs getRootConfigClasses() when extending AbstractAnnotationConfigDispatcherServletInitializer

What is the difference between getServletConfigClasses() vs getRootConfigClasses() when extending AbstractAnnotationConfigDispatcherServletInitializer.
I've been reading a lot sources since this morning but I haven't get any clear understanding on the differences yet :
Please have look at these two configurations :
1).
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ConServlet.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
....
....
}
The ConServlet.class is refering to
#EnableWebMvc
#Configuration
#ComponentScan({ "com" })
#Import({ SecurityConfig.class })
public class ConServlet {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
2).
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
.....
}
the WebConfig.class is refering to
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "....." })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
I see both ConServlet & WebConfig (more or less) doing the same things like initializating view :
But why :
ConServlet is returned in getRootConfigClasses()
while WebConfig is returned in getServletConfigClasses()
I read the documentation
both getRootConfigClasses() & getServletConfigClasses() is for
Specify #Configuration and/or #Component classes to be provided to..
(their differences )
the root application context for getRootConfigClasses()
the dispatcher servlet application context for getServletConfigClasses()
but why then ConServlet & WebConfig doing same things (like initizialising view), maybe I'm the one misunderstood it. What's are actually root context and dispatcher servlets (I know this one) in the simple term/example
Thank you!
A Bit on ApplicationContext Hierarchies
Spring's ApplicationContext provides the capability of loading multiple (hierarchical) contexts, allowing each to be focused on one particular layer, such as the web layer of an application or middle-tier services.
One of the canonical examples of using hierarchical ApplicationContext is when we have multiple DispatcherServlets in a web application and we're going to share some of the common beans such as datasources between them. This way, we can define a root ApplicationContext that contain all the common beans and multiple WebApplicationContexts that inherit the common beans from the root context.
In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to a given Servlet instance.
Typical context hierarchy in Spring Web MVC (Spring Documentation)
If you're living in a single DispatherServlet world, it is also possible to have just one root context for this scenario:
Single root context in Spring Web MVC (Spring Documentation)
Talk is cheap, Show me the code!
Suppose we're developing a web application and we're going to use Spring MVC, Spring Security and Spring Data JPA. For this simple scenario, we would have at least three different config files. A WebConfig that contains all our web related configurations, such as ViewResolvers, Controllers, ArgumentResolvers, etc. Something like following:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "com.so.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void configurePathMatch(PathMatchConfigurer configurer) {
final boolean DO_NOT_USE_SUFFIX_PATTERN_MATCHING = false;
configurer.setUseSuffixPatternMatch(DO_NOT_USE_SUFFIX_PATTERN_MATCHING);
}
}
Here I'm defining a ViewResolver to resolve my plain old jsps, poor life decisions, basically. We would need a RepositoryConfig, which contains all the data access facilities such as DataSource, EntityManagerFactory, TransactionManager, etc. It probably would be like following:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.so.repository")
public class RepositoryConfig {
#Bean
public DataSource dataSource() { ... }
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { ... }
#Bean
public PlatformTransactionManager transactionManager() { ... }
}
And a SecurityConfig which contains all the security related stuff!
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
#Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }
#Override
protected void configure(HttpSecurity http) throws Exception { ... }
}
For gluing all these together, we have two options. First, we can define a typical hierarchical ApplicationContext, by adding RepositoryConfig and SecurityConfig in root context and WebConfig in their child context:
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RepositoryConfig.class, SecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Since we have a single DispatcherServlet here, we can add the WebConfig to the root context and make the servlet context empty:
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RepositoryConfig.class, SecurityConfig.class, WebConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Further Reading
Skaffman did a great job on explaining ApplicationContext hierarchies in this answer, which is highly recommended. Also, you can read Spring Documentation.
Root Config Classes are actually used to Create Beans which are Application Specific and which needs to be available for Filters (As Filters are not part of Servlet).
Servlet Config Classes are actually used to Create Beans which are DispatcherServlet specific such as ViewResolvers, ArgumentResolvers, Interceptor, etc.
Root Config Classes will be loaded first and then Servlet Config Classes will be loaded.
Root Config Classes will be the Parent Context and it will create a ApplicationContext instace. Where as Servlet Config Classes will be the Child Context of the Parent Context and it will create a WebApplicationContext instance.
In your ConServlet Configuration, You don't need to specify the #EnableWebMvc as well the InternalResourceViewResolver bean as they are only required at the WebConfig.

Categories