blog.Ring.idv.tw

Apache Tomcat 8 + SQLite

Apache Tomcat 8 + SQLite


很長一段時間沒有更新該Blog了,由於最近為了做一些side project,所以打算在Mac筆電上架個簡單的開發環境,初步就想說直接利用SQLite來當做資料庫,反正只要中間層的DAO設計好,未來要改個後端也不是什麼太大的負擔,所以更不需要動到HBase之類的儲存方案。所以本文就純粹當作Memo...

必要軟體

.Apache Tomcat 8.5.43

為什麼選擇Tomcat 8的理由是,由於筆電的Java版本為Java 7,加上沒有急著升級的必要,所以就維持著...

至於SQLite的話,直接下載SQLite JDBC Driver即可,目前最新版本為sqlite-jdbc-3.27.2.1.jar

接下來就一步步地做些必要的操作:

修改 /etc/hosts

127.0.0.1    helloworld

這步驟主要是用來方便在筆電端快速地來做測試而已,上述的【helloworld】你可以改成你任意喜歡的,之後要測試時就直接在網頁上輸入http://helloworld:8080即可。

建立必要的目錄及檔案

$TOMCAT_HOME/helloworld/ROOT

$TOMCAT_HOME/helloworld/ROOT/index.jsp

上述index.jsp檔案裡任意寫個Hello JSP之類的文字即可。

修改 $TOMCAT_HOME/conf/server.xml

<Host name="helloworld"  appBase="helloworld"  unpackWARs="true" autoDeploy="true">
	     <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="helloworld_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
</Host>

啟動Tomcat

在啟動之前,如果你也是在Unix-like系統下安裝的話,那你可以考慮刪除掉$TOMCAT_HOME/bin/目錄底下的所有.bat檔案,這樣在透過Tab鍵補字操作下會方便些。

$TOMCAT_HOME/bin/startup.sh

接著在網頁上輸入http://helloworld:8080,應該就可以work了,接下來處理SQLite資料庫的部份。

建立必要的目錄及檔案

$TOMCAT_HOME/helloworld/ROOT/META-INF/context.xml

$TOMCAT_HOME/helloworld/ROOT/WEB-INF/classes

$TOMCAT_HOME/helloworld/ROOT/WEB-INF/lib

P.S. 請將sqlite-jdbc-3.27.2.1.jar直接copy到$TOMCAT_HOME/helloworld/ROOT/WEB-INF/lib/目錄下,至於其它目錄及檔案,待會再說明。

修改 META-INF/context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Resource name="jdbc/helloworld" auth="Container" type="javax.sql.DataSource" driverClassName="org.sqlite.JDBC"
            url="jdbc:sqlite:/Users/yourname/apache-tomcat-8.5.43/helloworld/ROOT/helloworld.db"
            factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory">
  </Resource>
</Context>

上述的【url】用來設定SQLite的檔案位置,接著會透過下面的Servlet程式來操作該資料庫。

建立一個 Servlet 程式

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.sql.*;

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");
		
		PrintWriter out = resp.getWriter();
		Connection con = null;
		ResultSet rs = null;
		PreparedStatement ps = null;

		try
		{
			Context ctx = new InitialContext();
			DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/helloworld");
			con =  ds.getConnection();

			Statement stat = con.createStatement();
			stat.executeUpdate("drop table if exists member;");
			stat.executeUpdate("create table member (id, name);");
			ps = con.prepareStatement("insert into member values (?, ?);");

			ps.setInt(1, 1);
			ps.setString(2, "Tony Lee");
			ps.addBatch();
			ps.setInt(1, 2);
			ps.setString(2, "Jack Wang");
			ps.addBatch();
			ps.executeBatch();


			rs = stat.executeQuery("select * from member;");
			while (rs.next()) {
				out.println("ID=" + rs.getInt("id")+"<br/>");
				out.println("Name=" + rs.getString("name")+"<br/>");
			}

		}catch (SQLException e)
		{
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			out.flush();
			out.close();

			try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
			try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
			try { con.close(); } catch (SQLException e) { e.printStackTrace(); }
		}
	}
}

最後將上述程式編譯後,將HelloServlet.class檔案copy至$TOMCAT_HOME/helloworld/ROOT/WEB-INF/classes/目錄下。

重新啟動Tomcat,輸入網址http://helloworld:8080/HelloServlet就可以看到下述結果:

ID=1
Name=Tony Lee
ID=2
Name=Jack Wang

2019-07-24 19:49:43

Leave a Comment

Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment