mysql-connector-java-8.0.18.zip
from the official website (https://dev.mysql.com/downloads/connector/j/) mysql-connector-java-5.1.48-bin.jar
/ WebContent / WEB-INF / lib / mysql-connector-java-5.1.48-bin.jar
Create in / WebContent / META-INF / context.xml
context.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
<Resource name = "jdbc/book"
auth = "Container"
type = "javax.sql.DataSource"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/book"
username = "namari"
password = "password">
</Resource>
</Context>
Create in /Sample/webapps/book/WEB-INF/src/chapter14/All.java
All.java
package chapter14;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.naming.InitialContext;
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.*;
/**
* Servlet implementation class All
*/
@WebServlet("/All")
public class All extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public All() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
//Get connection
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:/comp/env/jdbc/book");
Connection con = ds.getConnection();
//SQL statement transmission
PreparedStatement st = con.prepareStatement("select * from product");
//Execution & result reception
ResultSet rs = st.executeQuery();
//Data display
while (rs.next()) {
out.println(rs.getInt("id") + ":" + rs.getString("name") + ":" + rs.getInt("price"));
}
//Database disconnection
st.close();
con.close();
} catch (Exception e) {
//Connection / SQL statement error
e.printStackTrace(out);
} // try
}
}
Recommended Posts