サーバーサイドにJavaを利用しMySQLからデータを取得し一覧表示する処理のサンプル
[作成]
1.MySQLでデータベース[lunchapp]を作成する。

CREATE DATABASE lunchapp
DEFAULT CHARACTER SET utf8;

2.データベースlunchappに[lunches]テーブルを作成する。

CREATE TABLE lunches(
 id INT PRIMARY KEY AUTO_INCREMENT,
 name VARCHAR(30),
 menu VARCHAR(30)
 );

3.初期データを挿入しておく

INSERT INTO lunches(name,menu)VALUES
 ("subway","チリチキン"),("はなまる","かけうどん(小)"),("吉野家","牛丼(並)")

;

4.エクリプス。新規動的プロジェクトより「lunchapp」を作成する。
5.WEB-INF/lib/の中にJDBC,META-INFの直下にcontext.xmlを配置する。(詳しくは前回の記事参照)

<?xml version="1.0" encoding="UTF-8" ?>
<Context>
  <Resource
      name="jdbc/jsp"
      auth="Container"
      type="javax.sql.DataSource"
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/lunchapp"
      connectionProperties="autoReconnect=true;verifyServerCertificate=false;useSSL=false;requireSSL=false;useUnicode=true;characterEncoding=UTF-8;"
      username="root"
      validationQuery="select 1"/>
 </Context>

6.modelパッケージにLunch.javaを作成する。
●model.Lunch.java

package model;

import java.io.Serializable;

public class Lunch  implements Serializable{
	private int id;
	private String name;
	private String menu;
	public Lunch() {}
	public Lunch(int id,String name,String menu) {
		this.id=id;
		this.name=name;
		this.menu=menu;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMenu() {
		return menu;
	}
	public void setMenu(String menu) {
		this.menu = menu;
	}

}


「Logic作成」
7.modelパッケージ内にLunchLogic.javaを作成する。
●model.LunchLogic.java

package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class LunchLogic {
	public List<Lunch> findAll(){
		List<Lunch> list=new ArrayList<>();
		Connection db=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			Context context=new InitialContext();
			DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/jsp");
			db=ds.getConnection();
			ps=db.prepareStatement("SELECT * FROM lunches");
			rs=ps.executeQuery();
			while(rs.next()) {
				int id=rs.getInt("id");
				String name=rs.getString("name");
				String menu=rs.getString("menu");
				Lunch l=new Lunch(id,name,menu);
				list.add(l);
			}

		} catch (NamingException e) {
			
			e.printStackTrace();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				ps.close();
				db.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}


8.controllerパッケージ内にTest.java(Servlet)を作成

package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
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 model.Lunch;
import model.LunchLogic;

/**
 * Servlet implementation class Test
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LunchLogic ll=new LunchLogic();
		List<Lunch> list=ll.findAll();
		//System.out.println(list.size());
		request.setAttribute("list", list);
		RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/view/test.jsp");
		rd.forward(request, response);
	}
}

9./WEB-INF/viewフォルダにtest.jspを作成
●test.jsp(/WEB-INF/view/test.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="model.*,java.util.*"%>
<%
List<Lunch> list=(List<Lunch>)request.getAttribute("list");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%if(list !=null && list.size() > 0) {%>
<table border="1">
<%for(Lunch lunch:list){ %>
<tr>
<td><%=lunch.getId() %></td>
<td><%=lunch.getName() %></td>
<td><%=lunch.getMenu() %></td>
</tr>
<%} %>
</table>
<%} %>
</body>
</html>

10.Test.javaをサーバーで実行する。(以下のようになることを確認)

インサート

model.LunchLogic.java(insertOneメソッドを追記)

package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class LunchLogic {
	public List<Lunch> findAll(){
		List<Lunch> list=new ArrayList<>();
		Connection db=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			Context context=new InitialContext();
			DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/jsp");
			db=ds.getConnection();
			ps=db.prepareStatement("SELECT * FROM lunches");
			rs=ps.executeQuery();
			while(rs.next()) {
				int id=rs.getInt("id");
				String name=rs.getString("name");
				String menu=rs.getString("menu");
				Lunch l=new Lunch(id,name,menu);
				list.add(l);
			}

		} catch (NamingException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();
		}finally {
			try {
				rs.close();
				ps.close();
				db.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	public void insertOne(Lunch lunch) {
		Connection db=null;
		PreparedStatement ps=null;
		try {
			Context context = new InitialContext();
			DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/jsp");
			db=ds.getConnection();
			ps=db.prepareStatement("INSERT INTO lunches(name,menu) VALUES(?,?)");
			ps.setString(1, lunch.getName());
			ps.setString(2, lunch.getMenu());
			ps.executeUpdate();
		} catch (NamingException | SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}finally {
			try {
			ps.close();
			db.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}

	}
}

〇controller.TestInsert.java

package controller;

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;

import model.Lunch;
import model.LunchLogic;

/**
 * Servlet implementation class TestInsert
 */
@WebServlet("/TestInsert")
public class TestInsert extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/form.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("name");
		String menu=request.getParameter("menu");
		Lunch lunch=new Lunch(name,menu);
		LunchLogic ll=new LunchLogic();
		ll.insertOne(lunch);
		response.sendRedirect("/lunchapp/Test");
	}

}

〇/WEB-INF/view/form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/lunchapp/TestInsert" method="post">
なまえ:<input type="text" name="name"><br>
メニュー:<input type="text" name="menu"><br>
<input type="submit" value="登録">
</form>
</body>
</html>

11.TestInsertを実行してデータが挿入できればOK