飞道的博客

java篇-(java使用内嵌Tomcat开发javaWeb项目-初级篇)

545人阅读  评论(0)

写在前面

本项目使用开发软件为idea,版本控制使用maven,同时支持kotlin

初始化项目

使用idea构建kotlin项目

这里点击file,选择new project,然后选择kotlin,输入右侧一些信息之后,选择next

然后选择与上面jdk一样的版本,点击finish

pom.xml文件如下

这里添加tomcat-embed-core依赖,同时添加java编译插件,让java文件拥有11的新特性

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>embed-tomcat-example</artifactId>
    <groupId>com.lhstack</groupId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <name>embed-tomcat-example</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <kotlin.code.style>official</kotlin.code.style>
        <kotlin.compiler.jvmTarget>11</kotlin.compiler.jvmTarget>
        <tomcat.embed.version>9.0.31</tomcat.embed.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test-junit</artifactId>
            <version>1.4.10</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.embed.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>1.4.10</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>mavenCentral</id>
            <url>https://repo1.maven.org/maven2/</url>
        </repository>
    </repositories>

    <build>
        <sourceDirectory>src/main/kotlin</sourceDirectory>
        <testSourceDirectory>src/test/kotlin</testSourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <target>11</target>
                    <source>11</source>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>1.4.10</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

启动tomcat服务

使用java语言

package com.lhstack.embed;

import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lhstack
 */
public class EmbedTomcatApplication {
   
    public static void main(String[] args) throws Exception {
   
        //tomcat监听端口
        int port = 8080;
//        //tomcat的baseDir,如果是内嵌的,不需要启动war包项目,可以不需要设置此参数,这里就说明一下,不做配置
//        String baseDir = System.getProperty("user.dir") + "/tomcat";
//        //这里tomcat需要读取baseDir下面的webapps目录,并不会自动创建,所以需要单独处理一下,如果不需要启动war包项目,可以不做配置
//        String webapps = baseDir + "/webapps";
//        //创建目录
//        File file = new File(webapps);
//        if(!file.exists()){
   
//            file.mkdirs();
//        }
        Tomcat tomcat = new Tomcat();
        //tomcat.setBaseDir();

        tomcat.setPort(port);
        //需要设置一下端口,不然无法访问
        tomcat.getConnector().setPort(port);

        //创建一个context
        tomcat.addContext("/", Thread.currentThread().getContextClassLoader().getResource("").getFile());

        //创建servlet,指向上面创建的context,通过contextPath判断
        Wrapper servlet = tomcat.addServlet("/", "HelloServlet", new HttpServlet() {
   
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
                resp.getOutputStream().print("hello world");
            }
        });
        //添加映射
        servlet.addMapping("/");

        //启动tomcat
        tomcat.start();

    }
}

通过浏览器访问 localhost:8080

使用kotlin语言

package com.lhstack.embed

import org.apache.catalina.startup.Tomcat
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

fun main() {
   
    val port:Int = 8080
    val tomcat:Tomcat = Tomcat()
    tomcat.setPort(port)
    tomcat.connector.port = port
    tomcat.addContext("/",Thread.currentThread().contextClassLoader.getResource("")!!.path)
    val servlet = tomcat.addServlet("/", "HelloServlet", object : HttpServlet() {
   
        override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) {
   
            resp!!.outputStream.print("hello world")
        }
    })
    servlet.addMapping("/")
    tomcat.start()
}

启动后访问 localhost:8080

添加过滤器

使用java语言

		...
		...
        //添加映射
        servlet.addMapping("/");

        String encoding = "UTF-8";

        //定义filter
        FilterDef filterDef = new FilterDef();
        filterDef.setFilterName("CharacterEncodingFilter");
        filterDef.setFilter((req, res, chain) -> {
   
            if(req instanceof HttpServletRequest){
   
                System.out.println("setting request character encoding");
                req.setCharacterEncoding(encoding);
            }
            if(res instanceof HttpServletResponse){
   
                System.out.println("setting response character encoding");
                res.setCharacterEncoding(encoding);
            }
            chain.doFilter(req,res);
        });

        //定义filter映射
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName("CharacterEncodingFilter");
        filterMap.addURLPattern("/*");

        //添加filter
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);

        //启动tomcat
        tomcat.start();

    }
}

启动应用,查看浏览器和控制台

使用kotlin语言

	...
	...
    val encoding = "UTF-8"
    val filterDef = FilterDef()
    filterDef.filterName = "CharacterFilterEncoding"
    filterDef.filter = Filter {
    req, res, chain ->
        if(req is HttpServletRequest){
   
            println("setting request character encoding $encoding")
            req.characterEncoding = encoding
        }
        if(res is HttpServletResponse){
   
            println("setting response character encoding $encoding")
            res.characterEncoding = encoding
        }
        chain.doFilter(req,res)
    }

    val filterMap = FilterMap()

    filterMap.addURLPattern("/*")
    filterMap.filterName = "CharacterFilterEncoding"

    context.addFilterDef(filterDef)
    context.addFilterMap(filterMap)

    tomcat.start()
}

启动应用,查看浏览器和控制台

自定义sessionId生成器

使用java语言

		...
		...
        //创建一个context
        Context context = tomcat.addContext("/", Thread.currentThread().getContextClassLoader().getResource("").getFile());

        //添加context管理器 TODO
        StandardManager standardManager = new StandardManager();
        standardManager.setSessionIdGenerator(new SessionIdGeneratorBase() {
   
            @Override
            public String generateSessionId(String route) {
   
                return "lhstack-uuid->" + route + "->" + UUID.randomUUID().toString().replaceAll("-","");
            }
        });
        context.setManager(standardManager);
        
        ...
        ...

        //启动tomcat
        tomcat.start();

    }
}

启动项目,通过浏览器查看,session id

使用kotlin语言

	...
	...
    val context = tomcat.addContext("/", Thread.currentThread().contextClassLoader.getResource("")!!.path)
    ...
    ...
    //添加context关联器
    context.manager = StandardManager()

    context.manager.sessionIdGenerator = object:SessionIdGeneratorBase(){
   
        override fun generateSessionId(route: String?): String {
   
            return "lhstack->uuid->${UUID.randomUUID().toString().replace("-","")}"
        }
    }
    ...
    ...
    tomcat.start()
}

启动项目,通过浏览器查看,session id

添加模板引擎的支持

添加thymeleaf支持

添加pom依赖

在pom.xml添加如下依赖

<dependency>
   <groupId>org.thymeleaf</groupId>
   <artifactId>thymeleaf</artifactId>
   <version>${thymeleaf.version}</version>
</dependency>

添加thymeleaf支持的Servlet

使用java语言

		...
		//这里修改之前第一个创建的servlet,选择转发的方式
		//创建一个context
        Context context = tomcat.addContext("/", Thread.currentThread().getContextClassLoader().getResource("").getFile());

        //创建servlet,指向上面创建的context,通过contextPath判断
        Wrapper servlet = tomcat.addServlet("/", "HelloServlet", new HttpServlet() {
   
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
                //修改之前的输出,这里为了测试模板引擎的功能,所以选择转发
                req.getRequestDispatcher("index.html").forward(req,resp);
            }
        });
        //添加映射
        servlet.addMapping("/");
        ...

添加创建thymeleaf servlet的静态方法

public static void addThymeleafServlet(Context context,Tomcat tomcat){
   
		//这里context上下文,thymeleaf会去加载context的docBase目录下面的资源,所以之前我在创建context时,添加了当前classpath路径作为docBase路径
        ServletContext servletContext = context.getServletContext();
        ServletContextTemplateResolver contextTemplateResolver = new ServletContextTemplateResolver(servletContext);
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.addTemplateResolver(contextTemplateResolver);
        Tomcat.addServlet(context, "ThymeleafServlet", new HttpServlet() {
   
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
                DispatcherType dispatcherType = req.getDispatcherType();
                resp.setContentType("text/html;charset=utf-8");
                try{
   
                    String html = null;
                    if(dispatcherType == DispatcherType.FORWARD){
   
                        //如果是forward,就转发到受保护的template目录下面
                        html = templateEngine.process("/template" + req.getRequestURI(),new WebContext(req,resp,servletContext));
                    }else if(dispatcherType == DispatcherType.REQUEST){
   
                        //如果是普通请求,就映射static目录
                        html = templateEngine.process("/static" + req.getRequestURI(),new WebContext(req,resp,servletContext));
                    }
                    resp.getOutputStream().print(html);
                }catch (Exception e){
   
                    resp.getOutputStream().print("404 not found");
                }
            }
        }).addMapping("*.html");
    }

调用添加thymeleafServlet的方法

		...
		//添加filter
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);
		//这里调用添加thymeleafServlet的方法
        addThymeleafServlet(context,tomcat);

        //启动tomcat
        tomcat.start();

在对应目录添加html文件
resources/static

resources/template

通过浏览器测试
访问静态路径

访问根路径,通过HelloServlet进行转发

使用Kotlin语言

	...
	val context = tomcat.addContext("/", Thread.currentThread().contextClassLoader.getResource("")!!.path)
    val servlet = tomcat.addServlet("/", "HelloServlet", object : HttpServlet() {
   
        override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) {
   
            //修改之前的输出,这里为了测试模板引擎的功能,所以选择转发
            req!!.getRequestDispatcher("index.html").forward(req,resp)
        }
    })
    ...

添加addThymeleafServlet函数

fun addThymeleafServlet(context: Context){
   
    val servletContextTemplateResolver = ServletContextTemplateResolver(context.servletContext)
    val templateEngine = TemplateEngine()
    templateEngine.addTemplateResolver(servletContextTemplateResolver)
    Tomcat.addServlet(context,"ThymeleafServlet",object:HttpServlet(){
   
        override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) {
   
            val dispatcherType = req!!.dispatcherType
            resp!!.contentType = "text/html;charset=utf-8"
            try {
   
                var html: String? = null
                if (dispatcherType == DispatcherType.FORWARD) {
   
                    //如果是forward,就转发到受保护的template目录下面
                    html = templateEngine.process("/template" + req.requestURI, WebContext(req, resp, servletContext))
                } else if (dispatcherType == DispatcherType.REQUEST) {
   
                    //如果是普通请求,就映射static目录
                    html = templateEngine.process("/static" + req.requestURI, WebContext(req, resp, servletContext))
                }
                resp.outputStream.print(html)
            } catch (e: Exception) {
   
                resp.outputStream.print("404 not found")
            }
        }
    }).addMapping("*.html")
    
}

调用添加thymeleafServlet的函数

	...
  	context.addFilterDef(filterDef)
    context.addFilterMap(filterMap)
    
    addThymeleafServlet(context)

    tomcat.start()
    ...

通过浏览器测试
访问静态路径

访问根路径,通过HelloServlet进行转发

使用freemarker

添加pom依赖

在pom.xml里面添加freemarker依赖

<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>${freemarker.version}</version>
</dependency>

添加FreemarkerServlet,并在启动类里面使用

使用java语言

1.创建用于渲染freemarker模板的servlet

package com.lhstack.embed.servlet;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author lhstack
 */
public class FreemarkerServlet extends HttpServlet {
   

    private Configuration configuration = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
   
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassLoaderForTemplateLoading(config.getServletContext().getClassLoader(),"");
        configuration.setEncoding(Locale.CHINA,"UTF-8");
        configuration.setDefaultEncoding("UTF-8");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
        doRender(req,resp);
    }

    /**
     * 统一渲染方法
     * @param req
     * @param resp
     */
    private void doRender(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   
        //创建用于模板引擎中使用的变量
        Map<String,Object> model = new HashMap<>(4);
        model.put("Request",req);
        model.put("Response",resp);
        model.put("Session",req.getSession());
        model.put("Context",req.getServletContext());
        resp.setContentType("text/html;charset=utf-8");
        try{
   
            Template template = configuration.getTemplate("template" + req.getRequestURI().replaceAll(".html","ftl"));
            template.process(model,resp.getWriter());
        }catch (Exception e){
   
            if(e instanceof TemplateNotFoundException){
   
                resp.getOutputStream().print("template not found");
            }else{
   
                resp.getOutputStream().print(e.getMessage());
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
        doRender(req,resp);
    }
}

2.使用FreemarkServlet
在启动类里面,添加freemarkerServlet

  		...
  		//添加filter
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);
		//这里注释调thymeleafServlet
        //addThymeleafServlet(context,tomcat);
        addFreemarkerServlet(context,tomcat);
        //启动tomcat
        tomcat.start();
        ...

3.addFreemarkerServlet方法

public static void addFreemarkerServlet(Context context,Tomcat tomcat){
   
        Wrapper servlet = Tomcat.addServlet(context, "FreemarkerServlet", new FreemarkerServlet());
        servlet.addMapping("*.html");
    }

4.创建对应的ftl模板文件

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
this is freemarker page ${Request.getRequestURI()}
</body>
</html>

5.启动项目,通过浏览器访问

使用kotlin语言

1.使用FreemarkServlet
在启动类里面添加刚刚创建的FreemarkerServlet.java

...
    filterMap.addURLPattern("/*")
    filterMap.filterName = "CharacterFilterEncoding"

    context.addFilterDef(filterDef)
    context.addFilterMap(filterMap)

    //addThymeleafServlet(context)

    addFreemarkerServlet(context)

    tomcat.start()
}
//这里是函数
fun addFreemarkerServlet(context:Context){
   
    val servlet = Tomcat.addServlet(context, "FreemarkerServlet", FreemarkerServlet())
    servlet.addMapping("*.html")
}
...

2.启动项目,通过浏览器访问

完整代码

java语言

FreemarkerServlet.java

package com.lhstack.embed.servlet;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author lhstack
 */
public class FreemarkerServlet extends HttpServlet {
   

    private Configuration configuration = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
   
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassLoaderForTemplateLoading(config.getServletContext().getClassLoader(),"");
        configuration.setEncoding(Locale.CHINA,"UTF-8");
        configuration.setDefaultEncoding("UTF-8");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
        doRender(req,resp);
    }

    /**
     * 统一渲染方法
     * @param req
     * @param resp
     */
    private void doRender(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   
        //创建用于模板引擎中使用的变量
        Map<String,Object> model = new HashMap<>(4);
        model.put("Request",req);
        model.put("Response",resp);
        model.put("Session",req.getSession());
        model.put("Context",req.getServletContext());
        resp.setContentType("text/html;charset=utf-8");
        try{
   
            Template template = configuration.getTemplate("template" + req.getRequestURI().replaceAll(".html",".ftl"));
            template.process(model,resp.getWriter());
        }catch (Exception e){
   
            if(e instanceof TemplateNotFoundException){
   
                resp.getOutputStream().print("template not found");
            }else{
   
                resp.getOutputStream().print(e.getMessage());
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
        doRender(req,resp);
    }
}

EmbedTomcatApplication.java

package com.lhstack.embed;

import com.lhstack.embed.servlet.FreemarkerServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lhstack
 */
public class EmbedTomcatApplication {
   
    public static void main(String[] args) throws Exception {
   
        //tomcat监听端口
        int port = 8080;
//        //tomcat的baseDir,如果是内嵌的,不需要启动war包项目,可以不需要设置此参数,这里就说明一下,不做配置
//        String baseDir = System.getProperty("user.dir") + "/tomcat";
//        //这里tomcat需要读取baseDir下面的webapps目录,并不会自动创建,所以需要单独处理一下,如果不需要启动war包项目,可以不做配置
//        String webapps = baseDir + "/webapps";
//        //创建目录
//        File file = new File(webapps);
//        if(!file.exists()){
   
//            file.mkdirs();
//        }
        Tomcat tomcat = new Tomcat();
        //tomcat.setBaseDir();

        tomcat.setPort(port);
        //需要设置一下端口,不然无法访问
        tomcat.getConnector().setPort(port);

        //创建一个context
        Context context = tomcat.addContext("/", Thread.currentThread().getContextClassLoader().getResource("").getFile());

        //创建servlet,指向上面创建的context,通过contextPath判断
        Wrapper servlet = tomcat.addServlet("/", "HelloServlet", new HttpServlet() {
   
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
                //修改之前的输出,这里为了测试模板引擎的功能,所以选择转发
                req.getRequestDispatcher("index.html").forward(req,resp);
            }
        });
        //添加映射
        servlet.addMapping("/");

        String encoding = "UTF-8";

        //定义filter
        FilterDef filterDef = new FilterDef();
        filterDef.setFilterName("CharacterEncodingFilter");
        filterDef.setFilter((req, res, chain) -> {
   

            if(req instanceof HttpServletRequest){
   
                System.out.println("setting request character encoding");
                req.setCharacterEncoding(encoding);
            }
            if(res instanceof HttpServletResponse){
   
                System.out.println("setting response character encoding");
                res.setCharacterEncoding(encoding);
            }
            chain.doFilter(req,res);
        });

        //定义filter映射
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName("CharacterEncodingFilter");
        filterMap.addURLPattern("/*");

        //添加filter
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);

        //addThymeleafServlet(context,tomcat);
        addFreemarkerServlet(context,tomcat);
        //启动tomcat
        tomcat.start();

    }

    public static void addFreemarkerServlet(Context context,Tomcat tomcat){
   
        Wrapper servlet = Tomcat.addServlet(context, "FreemarkerServlet", new FreemarkerServlet());
        servlet.addMapping("*.html");
    }

    public static void addThymeleafServlet(Context context,Tomcat tomcat){
   
        //这里context上下文,thymeleaf会去加载context的docBase目录下面的资源,所以之前我在创建context时,添加了当前classpath路径作为docBase路径
        ServletContext servletContext = context.getServletContext();
        ServletContextTemplateResolver contextTemplateResolver = new ServletContextTemplateResolver(servletContext);
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.addTemplateResolver(contextTemplateResolver);
        Tomcat.addServlet(context, "ThymeleafServlet", new HttpServlet() {
   
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
                DispatcherType dispatcherType = req.getDispatcherType();
                resp.setContentType("text/html;charset=utf-8");
                try{
   
                    String html = null;
                    if(dispatcherType == DispatcherType.FORWARD){
   
                        //如果是forward,就转发到受保护的template目录下面
                        html = templateEngine.process("/template" + req.getRequestURI(),new WebContext(req,resp,servletContext));
                    }else if(dispatcherType == DispatcherType.REQUEST){
   
                        //如果是普通请求,就映射static目录
                        html = templateEngine.process("/static" + req.getRequestURI(),new WebContext(req,resp,servletContext));
                    }
                    resp.getOutputStream().print(html);
                }catch (Exception e){
   
                    resp.getOutputStream().print("404 not found");
                }
            }
        }).addMapping("*.html");
    }
}

kotlin语言

package com.lhstack.embed

import com.lhstack.embed.servlet.FreemarkerServlet
import org.apache.catalina.Context
import org.apache.catalina.session.StandardManager
import org.apache.catalina.startup.Tomcat
import org.apache.catalina.util.SessionIdGeneratorBase
import org.apache.tomcat.util.descriptor.web.FilterDef
import org.apache.tomcat.util.descriptor.web.FilterMap
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.WebContext
import org.thymeleaf.templateresolver.ServletContextTemplateResolver
import java.lang.Exception
import java.util.*
import javax.servlet.DispatcherType
import javax.servlet.Filter
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

fun main() {
   
    val port:Int = 8080
    val tomcat:Tomcat = Tomcat()
    tomcat.setPort(port)
    tomcat.connector.port = port
    val context = tomcat.addContext("/", Thread.currentThread().contextClassLoader.getResource("")!!.path)
    val servlet = tomcat.addServlet("/", "HelloServlet", object : HttpServlet() {
   
        override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) {
   
            //修改之前的输出,这里为了测试模板引擎的功能,所以选择转发
            req!!.getRequestDispatcher("index.html").forward(req,resp)
        }
    })
    servlet.addMapping("/")

    //添加context关联器
    context.manager = StandardManager()

    context.manager.sessionIdGenerator = object:SessionIdGeneratorBase(){
   
        override fun generateSessionId(route: String?): String {
   
            return "lhstack->uuid->${UUID.randomUUID().toString().replace("-","")}"
        }
    }

    val encoding = "UTF-8"

    val filterDef = FilterDef()
    filterDef.filterName = "CharacterFilterEncoding"
    filterDef.filter = Filter {
    req, res, chain ->
        if(req is HttpServletRequest){
   
            println("setting request character encoding $encoding")
            req.characterEncoding = encoding
        }
        if(res is HttpServletResponse){
   
            println("setting response character encoding $encoding")
            res.characterEncoding = encoding
        }
        chain.doFilter(req,res)
    }

    val filterMap = FilterMap()

    filterMap.addURLPattern("/*")
    filterMap.filterName = "CharacterFilterEncoding"

    context.addFilterDef(filterDef)
    context.addFilterMap(filterMap)

    //addThymeleafServlet(context)

    addFreemarkerServlet(context)

    tomcat.start()
}

fun addFreemarkerServlet(context:Context){
   
    val servlet = Tomcat.addServlet(context, "FreemarkerServlet", FreemarkerServlet())
    servlet.addMapping("*.html")
}

fun addThymeleafServlet(context: Context){
   
    val servletContextTemplateResolver = ServletContextTemplateResolver(context.servletContext)
    val templateEngine = TemplateEngine()
    templateEngine.addTemplateResolver(servletContextTemplateResolver)
    Tomcat.addServlet(context,"ThymeleafServlet",object:HttpServlet(){
   
        override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) {
   
            val dispatcherType = req!!.dispatcherType
            resp!!.contentType = "text/html;charset=utf-8"
            try {
   
                var html: String? = null
                if (dispatcherType == DispatcherType.FORWARD) {
   
                    //如果是forward,就转发到受保护的template目录下面
                    html = templateEngine.process("/template" + req.requestURI, WebContext(req, resp, servletContext))
                } else if (dispatcherType == DispatcherType.REQUEST) {
   
                    //如果是普通请求,就映射static目录
                    html = templateEngine.process("/static" + req.requestURI, WebContext(req, resp, servletContext))
                }
                resp.outputStream.print(html)
            } catch (e: Exception) {
   
                resp.outputStream.print("404 not found")
            }
        }
    }).addMapping("*.html")

}

转载:https://blog.csdn.net/qq_42413011/article/details/116243975
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场