今天把原来的代码修改了一下,加入了BaseDao、BaseDaoImpl等接口和实现类,完成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上增加方法。
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类,增加了获取全部学生信息的方法。
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) { } }
以上是实现结果。
附:学习了如何做到IDEA中设置代码和浏览器同步
——》
这样在调试时就能做到同步。Run时还需要手动选择一下