Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package sample;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.servlet.http.HttpSession;
import sample.bean.DataBean;
/**
* Servlet implementation class SampleClass
*/
@WebServlet("/SampleClass")
public class SampleClass extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleClass() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//DBからデータ取得
getDB(request);
response.setCharacterEncoding("UTF-8");
ServletContext context = this.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
//AWSのEC2のSQLserver接続
private void getDB(HttpServletRequest request) {
try {
Driver d = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
//IPアドレスはEC2再起動の度に変わります
String connUrl =
"jdbc:sqlserver://XXX.XXX.XXX.XXX:1433;database=testdb;"
+ "user=testuser;password=password";
Connection con = d.connect(connUrl, new Properties());
String sql = "select * from Table_2;";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<DataBean> list = new ArrayList<DataBean>();
while (rs.next()) {
list.add(new DataBean(rs.getString("col1"), rs.getString("col2")));
}
request.setAttribute("dbdata", list);
rs.close();
stmt.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment