Announcement Announcement Module
Collapse
No announcement yet.
Spring 3.1 with No XML Not working Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • loki70x7
    started a topic Spring 3.1 with No XML Not working

    Spring 3.1 with No XML Not working

    So I've setup a spring mvc 3.1 project from scratch and am not using any xml. Thing is my controllers are not getting registered. There are no errors what so ever its like the controller doesn't exist.

    The index page loads when I run the application but when I try the url thats mapped nothing happens.
    The console shows no errors and I have no build errors.

    My Initializer class looks like this:

    Code:
    @Configuration
    public class Initializer implements WebApplicationInitializer
    {
    public void onStartup(ServletContext container) throws ServletException
    	{
    		logger.info("Loading..");
    		System.out.print("YALLO");
    		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    		rootContext.register(AppConfig.class);
    		
     
    		// Manage the lifecycle of the root application context
    		container.addListener(new ContextLoaderListener(rootContext));
     
    		// Create the dispatcher servlet's Spring application context
    		AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    		dispatcherContext.register(DispatcherConfig.class);
     
    		// Register and map the dispatcher servlet
    		ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
    		dispatcher.setLoadOnStartup(1);
    		dispatcher.addMapping("/"); 
    	}
    }

    My configuration class looks like this:
    Code:
    @Configuration
    @ComponentScan(basePackages = "com.yardy.controllers")
    public class DispatcherConfig
    {
    	private static final Logger logger = LoggerFactory.getLogger(DispatcherConfig.class);
    	
    	@Bean
    	public InternalResourceViewResolver configureInternalResourceViewResolver()
    	{
    		logger.error("HELLO");
    		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    		resolver.setPrefix("/WEB-INF/views/");
    		resolver.setSuffix(".jsp");
    		return resolver;
    	}
    }
    Controller looks like this:


    Code:
    package com.yardy.controllers;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    @Controller
    public class YardyController
    {
    	 private static final Logger logger = LoggerFactory.getLogger(YardyController.class);
    	 
    	 @RequestMapping(value = "/yardy")
    	 public String yardy()
    	 {
    		 System.out.print("Testing..");
    		logger.info("Welcome home!");
    		System.out.print("YARDY");
    		return "yardy";
    	 }
    }

    /yardy just 404's thou.

    Can anyone give me any insight into this.
    Perhaps point out something I'm missing.
    Last edited by loki70x7; Feb 6th, 2012, 07:50 AM.

  • buddha_314
    replied
    I had a very similar problem (where it looked like none of the controllers were getting loaded) and my answer was to use

    Code:
    dispatcher.addMapping("/myapp/*");
    with the "*". It looks like you are missing that. You seem to have dispatcher.addMapping("/");

    I hope this gets you back on track. Good luck!

    Leave a comment:


  • sah.lalbabu@gmail.com
    replied
    What app server (version) are you using?

    Leave a comment:


  • good141
    replied
    Normally if a request path is not mapped you would see it in the console logs but I don't see any errors at all. Attachment
    Attached Files

    Leave a comment:


  • sah.lalbabu@gmail.com
    replied
    Which app server / version you are running?
    If you're running tomcat, version <=7.0.14 does not support programmatially overriding the servlet mapping. That might be the reason it's not working. Your tomcat log doesn't seem to be showing that the handlers are registered either.

    Leave a comment:


  • loki70x7
    replied
    Originally posted by Marten Deinum View Post
    Make sure it is on the classpath (maybe it doesn't get properly deployed) also make sure that you don't have duplicate jars in your classpath (or in different locations) which might screwup class checking.
    No duplicate jars are present on the classpath and since its just a class in my application that implements WebApplicationInitializer that is expected I don't see why it wouldn't work.

    Is there any set of jars that "HAVE" to be present on the classpath?

    Currently I've added all the 3.1 Spring jars so I can't figure what could be missing...

    Leave a comment:


  • Marten Deinum
    replied
    Make sure it is on the classpath (maybe it doesn't get properly deployed) also make sure that you don't have duplicate jars in your classpath (or in different locations) which might screwup class checking.

    Leave a comment:


  • loki70x7
    replied
    INFO: No Spring WebApplicationInitializer types detected on classpath

    I have a class that implements WebApplicationInitializer with onStartup method overidden but it doesn't seem to get detected.
    What would cause this message to appear in the logs?

    Leave a comment:


  • Marten Deinum
    replied
    Judging by your path you are using tomcat6 not tomcat7.
    Code:
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Java\jdk1.6.0_26\bin;ANT_HOME%\bin;C:\Users\martin\Documents\Latitude\endeca-portal\tomcat-6.0.29\bin;.
    Also @scottyfred @Controllers and @RequestMappings are also used by the default settings in the DispatcherServlet (although the defaults aren't as powerful as @EnableWebMvc but it should still work).

    Leave a comment:


  • lyonyao
    replied
    i do it and it works.i post the code and you see it.I hope it can help you.
    Initializer.java
    Code:
    package com.acme.web;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.ContextLoaderListener;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    import org.springframework.web.servlet.DispatcherServlet;
    
    public class Initializer implements WebApplicationInitializer {
    
    	public void onStartup(ServletContext servletContext) throws ServletException {
    		// TODO Auto-generated method stub
    		
    		AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
    		servletContext.addListener(new ContextLoaderListener(mvcContext));
    		mvcContext.register(MvcConfig.class);
    		  ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
    		    "dispatcher", new DispatcherServlet(mvcContext));
    		  dispatcher.setLoadOnStartup(1);
    		  dispatcher.addMapping("/");
    	}
    
    }
    MvcConfig.java
    Code:
    package com.acme.web;
    
    import java.util.List;
    
    import javax.inject.Inject;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import org.springframework.context.annotation.Scope;
    import org.springframework.context.annotation.ScopedProxyMode;
    import org.springframework.context.support.ReloadableResourceBundleMessageSource;
    import org.springframework.core.env.Environment;
    import org.springframework.format.FormatterRegistry;
    import org.springframework.http.converter.ByteArrayHttpMessageConverter;
    import org.springframework.http.converter.FormHttpMessageConverter;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.StringHttpMessageConverter;
    import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
    import org.springframework.http.converter.xml.SourceHttpMessageConverter;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.DefaultMessageCodesResolver;
    import org.springframework.validation.Validator;
    import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
    import org.springframework.web.context.request.WebRequest;
    import org.springframework.web.context.request.WebRequestInterceptor;
    import org.springframework.web.filter.RequestContextFilter;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
    import org.springframework.web.multipart.MultipartResolver;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.ViewResolver;
    import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;
    
    import com.acme.DBConfig;
    
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.spring.my")
    @Import(DBConfig.class)
    public class MvcConfig  extends WebMvcConfigurerAdapter{
    	@Inject
    	private Environment environment;
    	@Bean
    	 public ViewResolver contentNegotiatingViewResolver() {
    	  InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
    	  internalResourceViewResolver.setPrefix("/views/");
    	  internalResourceViewResolver.setSuffix(".jsp");
    	  internalResourceViewResolver.setViewClass(JstlView.class);
    	  return internalResourceViewResolver;
    	 }
    	/**
    	 * Supports FileUploads.
    	 */
    	@Bean
    	public MultipartResolver multipartResolver() {
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    		multipartResolver.setMaxUploadSize(500000);
    		return multipartResolver;
    	}
    	@Override
    	public void addArgumentResolvers(
    			List<HandlerMethodArgumentResolver> argumentResolvers) {
    		
    	}
    	@Override
    	public void addFormatters(FormatterRegistry registry) {
    		
    	}
    	@Override
    	public void addInterceptors(InterceptorRegistry registry) {
    	}
    	@Override
    	public void addResourceHandlers(ResourceHandlerRegistry registry) {
    		registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    	}
    	@Override
    	public void addReturnValueHandlers(
    			List<HandlerMethodReturnValueHandler> returnValueHandlers) {
    		
    	}
    	@Override
    	public void addViewControllers(ViewControllerRegistry registry) {
    		registry.addViewController("dfdfdffd");
    	}
    	@Override
    	public void configureDefaultServletHandling(
    			DefaultServletHandlerConfigurer configurer) {
    //		configurer.enable();
    	}
    	@Override
    	public void configureHandlerExceptionResolvers(
    			List<HandlerExceptionResolver> exceptionResolvers) {
    		exceptionResolvers.add(new HandlerExceptionResolver() {
    			
    			@Override
    			public ModelAndView resolveException(HttpServletRequest arg0,
    					HttpServletResponse arg1, Object arg2, Exception arg3) {
    				// TODO Auto-generated method stub
    				return new ModelAndView("hello");
    			}
    		});
    	}
    	@SuppressWarnings("rawtypes")
    	@Override
    	public void configureMessageConverters(
    			List<HttpMessageConverter<?>> converters) {
    		
    		converters.add(new MappingJacksonHttpMessageConverter());
    		converters.add(new SourceHttpMessageConverter());
    		converters.add(new FormHttpMessageConverter());
    		converters.add(new StringHttpMessageConverter());
    		converters.add(new ByteArrayHttpMessageConverter());
    	}
    	@Override
    	public Validator getValidator() {
    		LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    		messageSource.setBasename("/WEB-INF/messages/validation");
    		if (environment.acceptsProfiles("embedded")) {
    			messageSource.setCacheSeconds(0);
    		}
    		System.out.println("-=-=-=-===-=");
    		factory.setValidationMessageSource(messageSource);
    		return factory;
    	}
    	@Bean
    	public DefaultMessageCodesResolver defaultMessageCodesResolver(){
    		return new DefaultMessageCodesResolver();
    	}
    }
    DBConfig.java
    Code:
    package com.acme;
    
    import javax.sql.DataSource;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.datasource.DriverManagerDataSource;
    
    @Configuration
    @ImportResource("classpath:/com/acme/properties-config.xml")
    public class DBConfig {
    	private @Value("${jdbc.driver}")
    	String driver;
    	private @Value("${jdbc.url}")
    	String url;
    	private @Value("${jdbc.username}")
    	String username;
    	private @Value("${jdbc.password}")
    	String password;
    	public @Bean
    	DataSource dataSource() {
    		System.out.println("OK-------------------------");
    		DriverManagerDataSource dataSource=new DriverManagerDataSource(url, username, password);
    		dataSource.setDriverClassName(driver);
    		return dataSource;
    	}
    	public @Bean
    	JdbcTemplate jdbcTemplate(){
    		return new JdbcTemplate(dataSource());
    		
    	}
    }
    UserController.java
    Code:
    package com.spring.my.web;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.validation.Valid;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.Validator;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.spring.my.entry.SysMenu;
    import com.spring.my.service.UserService;
    
    @Controller
    public class UserController {
    	@Resource private UserService userService;
    	@Resource private Validator validator;
    	@InitBinder
    	protected void initBinder(WebDataBinder binder){
    		binder.setValidator(validator);
    	}
    	@RequestMapping(value="/store/{good}/a.action",method=RequestMethod.GET)
    	public String  listSysMenu(@PathVariable String good,HttpServletRequest request){
    		System.out.println(good);
    		request.setAttribute("sys_menu", userService.listSysMenu());
    		return "hello";
    	}
    }
    Attachment Attachment
    Attached Files

    Leave a comment:


  • loki70x7
    replied
    Originally posted by scottyfred View Post
    Add the "@EnableWebMvc" annotation to your DispatcherConfig class (along with @Configuration and @ComponentScan) to enable all the Spring MVC annotation-based configuration goodies.
    I added that but no luck there.

    Are there any specific jar files that have to be in the lib folder?

    Leave a comment:


  • scottyfred
    replied
    Add the "@EnableWebMvc" annotation to your DispatcherConfig class (along with @Configuration and @ComponentScan) to enable all the Spring MVC annotation-based configuration goodies.

    Leave a comment:


  • loki70x7
    replied
    Also based on my reading I think I should see something like this in the console:

    INFO : org.springframework.web.SpringServletContainerInit ializer - Delegating ServletContext to the following WebApplicationInitializer instances: [[email protected] cd65]

    Meaning that the Initializer is going to be automatically bootstrapped by any Servlet 3.0 container
    Which I currently do not see.
    Anyone have any thoughts on why this would not occur?

    Leave a comment:


  • loki70x7
    replied
    Originally posted by Marten Deinum View Post
    Do you have a web.xml? Also check your logging if you see something starting or see errors, you might want to enable debug logging.
    I removed the web.xml and there are no errors thrown in the console log. Normally if a request path is not mapped you would see it in the console logs but I don't see any errors at all. I've also set the log level on TC to FINEST and still don't see anything.

    My log output is as follow:

    Code:
    6-Feb-2012 10:13:00 AM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Java\jdk1.6.0_26\bin;ANT_HOME%\bin;C:\Users\martin\Documents\Latitude\endeca-portal\tomcat-6.0.29\bin;.
    6-Feb-2012 10:13:00 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ASpring3.1' did not find a matching property.
    6-Feb-2012 10:13:00 AM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    6-Feb-2012 10:13:00 AM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
    6-Feb-2012 10:13:00 AM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 461 ms
    6-Feb-2012 10:13:00 AM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    6-Feb-2012 10:13:00 AM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.25
    6-Feb-2012 10:13:00 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8080"]
    6-Feb-2012 10:13:00 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    6-Feb-2012 10:13:00 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 287 ms

    Leave a comment:


  • Marten Deinum
    replied
    Do you have a web.xml? Also check your logging if you see something starting or see errors, you might want to enable debug logging.

    Leave a comment:

Working...
X