当前位置: 代码迷 >> 综合 >> Servlet3.0——整合SpringMVC的Demo
  详细解决方案

Servlet3.0——整合SpringMVC的Demo

热度:26   发布时间:2023-12-22 04:24:21.0

1、Spring容器:并不需要@Configuration注解

@ComponentScan(value = "com.bdm", excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) })
public class RootConfig {}

2、SpringMVC容器:并不需要@Configuration注解

@ComponentScan(value = "com.bdm", useDefaultFilters = false, includeFilters = {@Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) })
public class AppConfig {}

3、controller

@Controller
public class HelloController {@AutowiredHelloService helloService;@ResponseBody@RequestMapping("/hello")public String sayHello(){String sayHello = helloService.sayHello("tomcat");return sayHello;}
}

4、service

@Service
public class HelloService {public String sayHello(String name){return "Hello " + name;}
}

5、AbstractAnnotationConfigDispatcherServletInitializer的实现类

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[] { RootConfig.class };}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[] { AppConfig.class };}@Overrideprotected String[] getServletMappings() {return new String[] { "/" };}}

拦截的路径,此处配置的"/":表示拦截除*.jsp之外的所有请求,*.jsp的解析是由tomcat的jsp引擎负责的;若配置成"/*"则会连*.jsp也会拦截,导致jsp无法解析

6、访问:

  相关解决方案