- 需要的jar包:mysql-connector-java.jar
- build path只是個jar包的引用,部署的時候想不丟包最好還是手動拷貝到對應項目的lib文件下。
- 在try{}中定義的變量為局部變量。
- WEB-INF對於瀏覽器是無法直接通過url訪問的,因此要想跳轉到WEB-INF目錄下必須采用服務端的foward方法而不能采用redirect方法。
- 注意網頁的編碼問題,一般全采用utf-8就沒亂碼了。
- 注意pageContext,request,session,application對象的scope,作用范圍。
目錄結構為:
首先我們創建實體類:Student
package micro.entity; public class Student { String name; int no; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } }
- 創建dao,負責數據庫的連接與關閉:
-
package micro.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.PreparedStatement; public class Dao { public static Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/micro"; String username = "root"; String password = "root"; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); } catch(ClassNotFoundException e) { e.printStackTrace(); } return conn; } public static void close(ResultSet rs,PreparedStatement ps,Connection conn) throws SQLException { try { rs.close(); ps.close(); conn.close(); } catch(SQLException e) { e.printStackTrace(); } } }
- 創建查詢方法類(按名字查詢和按學號查詢):
-
package micro.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import micro.entity.Student; import com.mysql.jdbc.PreparedStatement; public class SearchDao { /** * @param micro * @return * @throws SQLException */ // static String sql = "select * from Student where ? = ?"; public static int getIdByName(String name) throws SQLException { int id = -1; try { Connection conn = Dao.getConnection(); PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select * from Student where name = ?"); // ps.setString(1, "name"); ps.setString(1, name); ResultSet rs = ps.executeQuery(); // List<Student> list = new ArrayList(); while (rs.next()) { id = rs.getInt("id"); } Dao.close(rs, ps, conn); } catch (SQLException e) { e.printStackTrace(); } return id; } /** * @param id * @return * @throws SQLException */ public static String getNameById(int id) throws SQLException { Connection conn; String name = null; try { conn = Dao.getConnection(); PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select * from Student where id = ?"); // ps.setString(1, ""); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); while (rs.next()) { name = rs.getString("name"); } Dao.close(rs, ps, conn); } catch (SQLException e) { e.printStackTrace(); } return name; } }
- 需要執行業務的servlet:
-
package micro.search; import java.io.IOException; import java.sql.SQLException; 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 micro.dao.SearchDao; /** * Servlet implementation class FindName */ @WebServlet("/FindName") public class FindNameOrNo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FindNameOrNo() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String username = request.getParameter("username"); int id = Integer.valueOf(request.getParameter("id")); if(!username.equals("")) { try { int no = SearchDao.getIdByName(username); request.setAttribute("id", no); } catch(SQLException e) { System.out.println("數據庫出現異常"); e.printStackTrace(); } request.getRequestDispatcher("/WEB-INF/IdResult.jsp").forward(request, response); } else { try { String name = SearchDao.getNameById(id); request.setAttribute("name", name); } catch(SQLException e) { System.out.println("數據庫出現異常"); e.printStackTrace(); } request.getRequestDispatcher("/WEB-INF/NameResult.jsp").forward(request, response); } } }
- welcome.jsp頁面:
-
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <form action="myQuery" method="post"> 請輸入學生姓名:<input type="text" name="username" /> <br /> 請輸入學生學號:<input type="text" name="id" /> <br /> <input type="submit" value="查詢" /> </form> </body> </html>
- 返回學號的頁面:
-
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h1> 查詢結果對應的學號為:<%= request.getAttribute("id") %> </h1> <form action="welcome.jsp" method = "post" > <input type = "submit" value = "返回" /> </form> </body> </html>
- 返回名字的頁面:
-
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h1> 該學號的同學名字為:<%=request.getAttribute("name")%> </h1> <form action="welcome.jsp" method="post"> <input type="submit" value="返回" /> </form> </body> </html>
- web.xml:
-
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>Query</servlet-name> <servlet-class>micro.search.FindNameOrNo</servlet-class> </servlet> <servlet-mapping> <servlet-name>Query</servlet-name> <url-pattern>/myQuery</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>welcome.jsp</welcome-file> </welcome-file-list> </web-app>