今天把原來的代碼修改了一下,加入了BaseDao、BaseDaoImpl等接口和實現類,完成java中反射機制,使得代碼更加結構化。還把鏈接數據庫的部分拆出來了,有效避免代碼冗餘問題。html
首先是數據庫鏈接代碼 java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionManager { public static Connection getConnection() { Connection conn = null; String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=S-T"; String username = "sa"; String password = "111"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("沒有找到文件"); } catch (SQLException e) { e.printStackTrace(); System.out.println("sql異常"); } return conn; } }
而後是數據庫操做DAO,它可以隔離業務邏輯代碼和數據訪問代碼。用戶類也能夠經過繼承,在基礎DAO上增長方法。sql
import java.util.List; public interface BaseDao<T> {//泛型,增刪查改都有;爲了方便我讓查找返回list List<T> select(T t,String sql); void add(T t); void update(T t); void delete(T t); }
BaseDaoImpl是對BaseDao的具體實現,注意其中泛型的使用數據庫
import com.alibaba.fastjson.JSONObject; import javax.jnlp.BasicService; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.sql.*; import java.util.ArrayList; import java.util.List; public class BaseDaoImpl<T> implements BaseDao<T> { private Connection conn; private Statement ps; private ResultSet rs; private Class<T> EntityClass;// 獲取實體類 // ParameterizedType pr; public BaseDaoImpl(Object o){ //ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); //EntityClass=(Class<T>) pt.getActualTypeArguments()[0]; EntityClass= (Class<T>) o.getClass(); } @Override public List<T> select(T t,String sql ){ Connection conn=null; conn=ConnectionManager.getConnection(); List<T> list=new ArrayList<>(); T obj=null; // System.out.println(EntityClass); Field fields[] = EntityClass.getDeclaredFields(); try { ps=conn.createStatement(); rs=ps.executeQuery(sql); while (rs.next()){ obj = EntityClass.newInstance(); //System.out.println(fields.length); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); fields[i].set(obj, rs.getObject(fields[i].getName())); } list.add(obj); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return list; } @Override public void add(Object o) { } @Override public void update(Object o) { } @Override public void delete(Object o) { } }
咱們既能夠直接使用這個類,也能夠繼承BaseDaoImpl類,實現一些新的函數。如UserDaoImpl類,增長了獲取所有學生信息的方法。json
import java.sql.*; import java.util.ArrayList; import java.util.List; public class StudentDaoImpl extends BaseDaoImpl<student> implements StudentDao{ Connection conn; Statement ps=null; List<student> students=new ArrayList<>(); String sql=null; ResultSet rs=null; public StudentDaoImpl(Object O) { super(O); } @Override public List<student> findAll() { sql="select * from Student"; conn=ConnectionManager.getConnection(); try { ps=conn.createStatement(); rs=ps.executeQuery(sql); // System.out.println(rs.getString(0)); while (rs.next()){ student st=new student(); st.setName(rs.getString("Sname")); st.setId(rs.getString("Sno")); st.setSex(rs.getString("Ssex")); st.setAge(rs.getString("Sage")); students.add(st); } } catch (SQLException e) { e.printStackTrace(); } return students; } }
最後是接口實現:瀏覽器
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import sun.rmi.runtime.Log; 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 java.io.IOException; import java.io.PrintWriter; import java.sql.*; import java.util.*; import java.util.Date; @WebServlet("/hello")//註解,免於在xml註冊,/hello表示在主頁後加/hello訪問此頁面 public class test extends HttpServlet { private String message; public void init() throws ServletException{ } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {//相應不帶參數的get List<student> students=new ArrayList<>(); Connection dbConn=null; //StudentDaoImpl impl=new StudentDaoImpl(); BaseDaoImpl im=new BaseDaoImpl(new student()); try { // 設置響應內容類型 response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); dbConn=ConnectionManager.getConnection(); String sql="select * from Student";//拼接SQL語句 //students=impl.findAll(); students=im.select(new student(),sql); String staNum="500"; status sta=new status(staNum, (students)); System.out.println(JSONObject.toJSONString(sta));//轉變爲json對象 response.getWriter().println(JSONObject.toJSONString(sta));//注意這裏不是控制檯輸出了,是HttpServletResponse,用於返回json給http請求方 //response.getWriter().println(request.getParameter("age"));*/ } finally { try {//關閉鏈接 if(dbConn!=null) { dbConn.close(); dbConn=null; } } catch(Exception ex) { } } } public void doPost(HttpServletRequest request, HttpServletResponse response) { } }
以上是實現結果。ide
附:學習瞭如何作到IDEA中設置代碼和瀏覽器同步函數
——》sqlserver
這樣在調試時就能作到同步。Run時還須要手動選擇一下學習