top / index / prev / next / target / source

2015-10-28 diary: Java Servlet シンプルサンプル

いがぴょん画像(小) 日記形式でつづる いがぴょんコラム ウェブページです。

Java Servlet シンプルサンプル

とてもシンプルな Java Servlet のサンプル

SimpleServlet.java

package simple;

import java.io.IOException;

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

@WebServlet(urlPatterns = { "/SimpleServlet" })
public class SimpleServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

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

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json; charset=UTF-8");

    final String reqString = req.getParameter("json");
    System.out.println("json: [" + reqString + "]");

    // TODO Do something.

    resp.getWriter()
        .write("{\"id\":\"20237\", \"name\":\"Taro Yamada\", \"drive\":[\"car\",\"bicycle\",\"train\"]}");
  }
}

build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="SimpleServlet" default="build" basedir=".">
  <target name="build" depends="dir,compile,jar,war" />

  <target name="war">
    <war destfile="tmp/simpleservlet.war" needxmlfile="false">
      <fileset dir="tmp">
        <include name="WEB-INF/**/*" />
      </fileset>
    </war>
  </target>

  <target name="jar">
    <jar destfile="tmp/WEB-INF/lib/simpleservlet.jar">
      <zipfileset dir="tmp/bin" includes="**/*" />
    </jar>
  </target>

  <target name="compile">
    <delete dir="bin" />
    <mkdir dir="bin" />
    <javac destdir="tmp/bin" debug="true" source="1.7" target="1.7" fork="true" encoding="UTF-8" includeantruntime="false">
      <classpath>
        <fileset dir="lib">
          <include name="javax.*.jar" />
        </fileset>
      </classpath>
      <src path="src/" />
      <include name="**/*.java" />
    </javac>
  </target>

  <target name="dir">
    <delete dir="tmp" />
    <mkdir dir="tmp" />
    <mkdir dir="tmp/bin" />
    <mkdir dir="tmp/WEB-INF/lib" />
  </target>
</project>

Delphi からRESTサーバーの呼び出し

このサーバーを Delphi から呼び出す例: http://d.hatena.ne.jp/igapyon/20151029

関係しそうな日記


この日記について