五分钟手动创建简易的serlvet程序

March 27, 2018
手动创建servlet servlet

字数:2194

这篇文章涉及以下几个问题:

创建Servlet程序

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    id="test2" 
    version="3.0">
    <display-name>test2</display-name>
    <servlet>
        <servlet-name>t2</servlet-name>
        <servlet-class>de.tao.T2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>t2</servlet-name>
        <url-pattern>/add_user</url-pattern>
    </servlet-mapping>
</web-app>
package de.tao;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class T2 extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("T2.doPost in");
    }
}

配置Nginx

新增server配置如下:

server {
    listen 80;
    server_name t2.tao.de;

    location / {
        proxy_set_header Host t2.tao.de;
        proxy_pass http://localhost:8080;
    }
}

运行命令nginx -s reload使配置生效。

配置Tomcat

在conf/server.xml文件里新增如下配置:

<Host name="t2.tao.de" appBase="">
    <Context path="" docBase="/var/www/web/t2" debug="0" reloadable="true"/>
</Host>

验证

启动Tomcat, 运行curl -X POST http://t2.tao.de/add_user,能看到控制台已经打印T2.doPost in,工程OK。 使用这个功能验证跨域的问题以及解决办法,见文章


loading