summary

먼저 아파치 톰캣이 이클립스에 연동되어있다고 가정한다.
서블릿으로 웹요청을 받아들여 디비랑 통신하기 위한 코드에 대한 템플릿이다. 

DB와의 통신은 서블릿 코드에서 DBConnect.java를 통해 디비에 접속하고 Dao를 통해 질의문을 작성한다.


template_server.zip

git

프로젝트 생성

이클립스 > File > New > Dynamic Web Project

서블릿 파일 생성

File > New > Servlet > 아래 코드

package templete_server.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

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

/**
 * Servlet implementation class GetData
 */
@WebServlet(name = "GetData", urlPatterns = { "/GetData" })
public class GetData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetData() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		/////////////////////////////////////////////////////////////////
		// HTML SOURCE CODE
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Servlet GetData</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Servlet GetData at " + request.getContextPath()
				+ "</h1>");
		out.println("<p>");
		out.println("get data : " + request.getParameter("id"));
		out.println("</body>");
		out.println("</html>");

		out.println("");
		// HTML SOURCE CODE
		/////////////////////////////////////////////////////////////////

		String id = request.getParameter("id");
		System.out.println(id);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}

DB Connect ( Mysql)

jdbc나 mysql 드라이버는 'WebContent > WEN-INF > lib' 안에 넣어주어야 한다.

첫 번째 코드는 DB를 연결하기 위함이고, 두 번째 코드는 질의문을 서버에 작성할 수 있다.


DBConnector.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnector {
	private String driver = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost:3306/dbschema?useUnicode=true&characterEncoding=UTF-8";
	private String user = "userid";	//DB user ID
	private String pwd = "password";	//DB user Password
	private Connection conn = null;
	
	public Connection getConnection(){
		try{
			Class.forName(driver);
		}catch(ClassNotFoundException e){
			System.out.println("BusInfoSystem : 드라이버 로딩 실패(getConnection)");
			System.out.println(e.getMessage());
		}
		try{
			conn = DriverManager.getConnection(url,user,pwd);
		}catch(SQLException e){
			System.out.println("BusInfoSystem : DB 연결 실패(getConnection)");
			System.out.println(e.getMessage());
		}
		return conn;
	}
}

tempateDao.java
package templete_server.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class templateDao {

	private DBConnector dbc;

	public templateDao() {
		dbc = new DBConnector();
	}

	public int getData(int arg1) {
		int result = 0;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = new String("select * from dbtable where ID = ?;");

		conn = dbc.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, arg1);
			rs = ps.executeQuery();
			rs.first();
			while (true) {
				result = rs.getInt("id");
				if (rs.isLast())
					break;
				rs.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(rs, ps, conn);
		}

		return result;
	}

	/**
	 * DataBase 자원 반환
	 * 
	 * @param rs
	 * @param ps
	 * @param conn
	 */
	private void closeDB(ResultSet rs, Statement ps, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (Exception e) {
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
			}
		}
	}
}


+ Recent posts