1.新建一个module,创建一个gradle的Java模块
2.项目完成之后,添加相关依赖
dependencies { compile fileTree(dir:'lib',includes: ['*jar'])
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '8.5.57'
compile project(":spring-context") compile project(":spring-webmvc")
testCompile group: 'junit', name: 'junit', version: '4.12' }
3.创建配置类Appconfig
@Configuration @ComponentScan("com.wk") public class Appconfig { }
4.创建启动类SpringApplicationWk
public class SpringApplicationWk { public static void run() throws ServletException, LifecycleException { //直接初始化spring容器 AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(Appconfig.class); context.refresh(); File base = new File(System.getProperty("java.io.tmpdir")); Tomcat tomcat = new Tomcat(); tomcat.setPort(9090); /** * addWebapp表示这是一个web项目 * contextPath Tomcat的访问路径 * 项目的web目录 * 所以这里不能用addWebapp(SpringBoot当中也没有这么做) * */ // tomcat.addWebapp("/","index.html"); Context rootContext = tomcat.addContext("/",base.getAbsolutePath()); DispatcherServlet dispatcherServlet = new DispatcherServlet(context); //这段话的作用是在Tomcat的启动过程中会调用DispatcherServlet.init()方法 //初始化controller和请求映射 Tomcat.addServlet(rootContext,"wk", (Servlet) dispatcherServlet).setLoadOnStartup(1); // rootContext.addServletMapping("/","wk"); rootContext.addServletMappingDecoded("/","wk"); tomcat.start(); tomcat.getServer().await(); } }
5.创建controller
@Controller public class IndexController { @RequestMapping("/index") @ResponseBody public String index(){ return "index"; } }
6.创建测试类
public class Test { public static void main(String[] args) { try { SpringApplicationWk.run(); } catch (ServletException e) { e.printStackTrace(); } catch (LifecycleException e) { e.printStackTrace(); } } }
7.启动项目,访问