Page 2 of 2 FirstFirst 12
Results 11 to 19 of 19

Thread: Spring 3.1 with No XML Not working

  1. #11
    Join Date
    Feb 2012
    Location
    xi'an China
    Posts
    4

    Default

    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";
    	}
    }
    QQ截图20120207114004.jpgQQ截图20120207114147.jpg
    love me,love my code

  2. #12
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    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).
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #13
    Join Date
    Feb 2012
    Posts
    9

    Default

    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?

  4. #14
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  5. #15
    Join Date
    Feb 2012
    Posts
    9

    Default

    Quote 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...

  6. #16
    Join Date
    Feb 2012
    Location
    Des Moines, IA
    Posts
    6

    Default

    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.
    Lal Sah

  7. #17
    Join Date
    Feb 2012
    Posts
    15

    Default

    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. g.gif

  8. #18
    Join Date
    Feb 2012
    Location
    Des Moines, IA
    Posts
    6

    Default

    What app server (version) are you using?
    Lal Sah

  9. #19
    Join Date
    Feb 2013
    Posts
    5

    Default

    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!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •