• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

手写springboot–依据原理(内置tomcat的手写,以及内置springmvc的手写)撰写

java 来源:RollinSpark 19次浏览

声明:本文针对于含有springboot基础上讲解,至少涉猎过springboot的原理。

一、首先我们先来复习下springboot的核心原理要点。

1.基于SpringMVC无配置文件(纯Java)完全注解化+内置tomcat-embed-core实现SpringBoot框架,Main函数启动。

2.SpringBoot核心快速整合第三方框架原理:Maven继承依赖关系

3.SpringBoot内嵌入tomcat-embed-core

4.SpringBoot采用SpringMVC注解版本实现无配置效果

PS:本文说的不是SpringBoot流程,而是SpringBoot核心原理

二、依据上述原理,我们可以知道主要需要实现内置tomcat和内置springmvc的手写

1、内置tomcat容器(Java提供内置Tomcat容器框架,使用Java语言操作Tomcat容器)
①、首先我们需要导入实现java内置tomcat的依赖

<dependencies>

           <!–Java语言操作tomcat –>

           <dependency>

                 <groupId>org.apache.tomcat.embed</groupId>

                 <artifactId>tomcat-embed-core</artifactId>

                 <version>8.5.16</version>

           </dependency>

           <!–spring-web –>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-web</artifactId>

                 <version>5.0.4.RELEASE</version>

                 <scope>compile</scope>

           </dependency>

           <!–spring-mvc –>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-webmvc</artifactId>

                 <version>5.0.4.RELEASE</version>

                 <scope>compile</scope>

           </dependency>

           <!– tomcatjsp支持 –>

           <dependency>

                 <groupId>org.apache.tomcat</groupId>

                 <artifactId>tomcatjasper</artifactId>

                 <version>8.5.16</version>

           </dependency>

      </dependencies>


②、然后手写创建一个Servlet

publicclass IndexServetextends HttpServlet {

      @Override

      protectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp) throwsServletException, IOException {

           doPost(req, resp);

      }

 

      @Override

      protectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp) throwsServletException, IOException {

           resp.getWriter().print(“springboot2.0 内置Tomcat的Servlet”);

      }

}

③、创建Tomcat进行运行(创建一个类 名为AppTomcat,复制下列代码)

//端口号


private static int port=9090;


//项目访问路径


private static String CONTACT_PATH=”/RollinSpark”;





public static void main(String[] args) {


start();


}


private static void start() {


// TODO Auto-generated method stub


//创建Tomcat服务器


Tomcat tomcat=new Tomcat();


//设置端口号


tomcat.setPort(port);


tomcat.getHost().setAutoDeploy(false);


// 创建Context上下文


StandardContext standardContext=new StandardContext();


standardContext.setPath(CONTACT_PATH);


standardContext.addLifecycleListener(new FixContextListener());





// tomcat容器添加standardContext


tomcat.getHost().addChild(standardContext);





// 创建servlet


tomcat.addServlet(CONTACT_PATH, “IndexServlet”, new IndexServlet());


// 添加servleturl映射


standardContext.addServletMappingDecoded(“/index”, “IndexServlet”);


try {


tomcat.start();


System.out.println(“tomcat启动成功…”);


} catch (LifecycleException e) {


// TODO Auto-generated catch block


e.printStackTrace();


System.out.println(“tomcat启动失败…”);


}


//服务阻塞等待

tomcat.getServer().await();

}


④、启动AppTomcat类,运行效,访问http://localhost:9090/RollinSpark/index可以看到效果






2、SpringMVC无注解启动方式回顾

DispatcherServlet是Spring MVC的核心,每当应用接受一个HTTP请求,由DispatcherServlet负责将请求分发给应用的其他组件。

在旧版本中,DispatcherServlet之类的servlet一般在web.xml文件中配置,该文件一般会打包进最后的war包种;但是Spring 3引入了注解,我们这节课讲解,如何基于注解配置Spring MVC。

3、整合SpringMVC和内置Tomcat实现SpringBoot的功能
①、新建Maven项目,设置为war工程
②、添加Maven依赖

<dependencies>

           <!–Java语言操作tomcat –>

           <dependency>

                 <groupId>org.apache.tomcat.embed</groupId>

                 <artifactId>tomcat-embed-core</artifactId>

                 <version>8.5.16</version>

           </dependency>

           <!–spring-web –>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-web</artifactId>

                 <version>5.0.4.RELEASE</version>

                 <scope>compile</scope>

           </dependency>

           <!–spring-mvc –>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-webmvc</artifactId>

                 <version>5.0.4.RELEASE</version>

                 <scope>compile</scope>

           </dependency>

           <!– tomcatjsp支持 –>

           <dependency>

                 <groupId>org.apache.tomcat</groupId>

                 <artifactId>tomcatjasper</artifactId>

                 <version>8.5.16</version>

           </dependency>

      </dependencies>


③、加载SpringMVCDispatcherServlet

package com.rollin.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**

 * 

 * @author rollin

 * 重写web容器配置

 * 加载SpringMVCDispatcherServlet

 *

 */

public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{


@Override


protected Class<?>[] getRootConfigClasses() {


// TODO Auto-generated method stub


return new Class[] { RootConfig.class };


}


@Override


protected Class<?>[] getServletConfigClasses() {


// TODO Auto-generated method stub


return new Class[] { WebConfig.class };


}


@Override


protected String[] getServletMappings() {


// TODO Auto-generated method stub


return new String[] { “/” };


}

}

④、加载SpringMVC容器

package com.rollin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @EnableWebMvc 开启SpringMVC功能<br>
 * @Configuration 配置<br>
 * @author rollin
 * 启动webmvc 配置及扫包范围设置
 *
 */

@Configuration
@EnableWebMvc
@ComponentScan(“com.rollin.controller”)
public class WebConfig extends WebMvcConfigurerAdapter{
// 创建SpringMVC视图解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(“/WEB-INF/views/”);
viewResolver.setSuffix(“.jsp”);
            //可以在JSP页面中通过${}访问beans
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}

}


⑤、RootConfig容器

package com.rollin.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
 * 
 * @author rollin
 * web根容器
 *
 */
@Configuration
@ComponentScan(basePackages = “com.rollin”)
public class RootConfig {

}


⑥、建立运行的AppTomcat类

package com.rollin;

import java.io.File;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixContextListener;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

/**
 * 
 * @author rollin
 *
 */
public class AppTomcat {
// 端口号
private static int port = 9090;

public static void main(String[] args) {
start();
}

private static void start() {
try {
// TODO Auto-generated method stub
// 创建Tomcat服务器
Tomcat tomcat = new Tomcat();
// 设置端口号
tomcat.setPort(port);
tomcat.getHost().setAutoDeploy(false);

// 创建Context上下文
// 读取项目路径
StandardContext ctx = (StandardContext) tomcat.addWebapp(“/”, new File(“src/main/webapp”).getAbsolutePath());
// 禁止重新载入
ctx.setReloadable(false);

// class文件读取地址
File additionWebInfClasses = new File(“target/classes”);
// 创建WebRoot
WebResourceRoot resources = new StandardRoot(ctx);
// tomcat内部读取Class执行
resources.addPreResources(
new DirResourceSet(resources, “/WEB-INF/classes”, additionWebInfClasses.getAbsolutePath(), “/”));

tomcat.start();
System.out.println(“tomcat启动成功…”);

// 服务阻塞等待
tomcat.getServer().await();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(“tomcat启动失败…”);
}

}

}

⑦、项目添加逻辑层

Service层:

package com.rollin.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
public String index() {
return “UserService 访问成功!!–RollinSpark”;
}

}

Controller层:

package com.rollin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.rollin.service.UserService;

@RestController
public class UserController {
@Autowired
private UserService userService;

@RequestMapping(value=”/userIndex”,produces = “text/html;charset=UTF-8”)
public String index() {
return userService.index();
}

}


本文到这里基本结束,集成JSP就省略了,大致就是配置视图解析器,然后跳转页面…..有需要DEMO的可以加我扣扣,2485290255,记得备注说明!!!


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)