자바 학생 정보 관리 시스템 디자인(2)

이 예 의 학생 정 보 는 데이터베이스 에 들 어 가 는 사 무 를 추가 합 니 다(사 무 를 제출 할 수 있 고,사 무 를 스크롤 백 할 수 있 으 며,로 컬 스 레 드 로 보완 할 수 있 습 니 다)

홈 페이지 index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <head>

 <title>      </title>
 </head>

 <body>
 <a href='<c:url value="/query"/>?cmd=query'>      </a>
 <br><br>
 <!-- 
 <a href="<c:url value='/StudServlet?cmd=save' />">      </a>
 -->
 <h2>      </h2>
 <form action='<c:url value="/query"/>?cmd=add' method="post">
   :<input type="text" name="name"/><br><br>

 <fieldset style="border: solid;border-color: red;width: 250px;">
  <legend>  1</legend>
    :<input type="text" name="book"/><br><br>
    :<input type="text" name="price"/>
 </fieldset>
 <br>
 <fieldset style="border: solid;border-color:green;width: 250px;">
  <legend>  2</legend>
    :<input type="text" name="book"/><br><br>
    :<input type="text" name="price"/>
 </fieldset>
 <br><br>
 <input type="submit" value="  "/><br><br>
 </form>
 </body>
</html>

공구 꾸러미
데이터베이스 연결 도구 ConnUtils 5.java 가 져 오기

package cn.hncu.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ConnUtils5 {

 //        ,    :               
 private static ThreadLocal< Connection> t=new ThreadLocal<Connection>();
 private final static List<Connection> pool=new ArrayList<Connection>();
 private static int SIZE;//       
 private ConnUtils5(){

 }
 static{
 Properties p=new Properties();
 try {
  //        Java        classpath      ,     JavaEE   。  Tomcat            
  //p.load( ClassLoader.getSystemClassLoader().getSystemResourceAsStream("jdbc.properties"));
//  p.load(ClassLoader.getSystemResourceAsStream("jdbc.properties"));

  //  Web   classpath      ,     
  p.load(ConnUtils3.class.getClassLoader().getResourceAsStream("jdbc.properties"));
  String driver=p.getProperty("driver");
  String url=p.getProperty("url");
  String name=p.getProperty("username");
  String pwd=p.getProperty("password");
  String ssize=p.getProperty("size");
  SIZE=Integer.parseInt(ssize);
  Class.forName(driver);
  for(int i=0;i<SIZE;i++){
  final Connection con=DriverManager.getConnection(url,name,pwd);
  System.out.println("con=="+con);
  //  conn.close()  
  //             conn  ,   close()       
  Object nCon=Proxy.newProxyInstance(
   ConnUtils3.class.getClassLoader(), 
   // conn.getClass().getInterfaces(), 
   //        ,                       (      ) 
   new Class[]{Connection.class}, 
   new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
     throws Throwable {
    if(method.getName().equals("close")){
     System.out.println("      :"+(Connection)proxy);
     pool.add((Connection)proxy);
     return null;
    }
    return method.invoke(con, args);
    }
  });
  pool.add((Connection)nCon);
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
 }
 public static synchronized Connection getConnection(){
 //  t  ,       ,                t 
 Connection con=t.get();
 if(con==null){

  if(pool.size()<=0){
  System.out.println("       ...");
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  return getConnection();
  }
  con=pool.remove(0);
  t.set(con);//  t 
 }

 return con;//      
 }


}

대리

package cn.hncu.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class TxProxy implements InvocationHandler {

 private Object srcObj=null;

 private TxProxy(Object srcObj) {
 this.srcObj = srcObj;
 }


 public static Object getProxy(Object srcObj){
 System.out.println("srcObj:"+srcObj);
 Object newObj=Proxy.newProxyInstance(
  TxProxy.class.getClassLoader(), 
  srcObj.getClass().getInterfaces(), 
  new TxProxy(srcObj));
 System.out.println("newObj:"+newObj);
 return newObj;
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
 Connection con=null;
 Object returnObj=null;
 try {
  con=ConnUtils5.getConnection();
  System.out.println("invoke      :"+con);
  con.setAutoCommit(false);

  returnObj=method.invoke(srcObj, args);

  System.out.println("      ...");
  con.commit();
 } catch (Exception e) {
  try {
  System.out.println("      ...");
  con.rollback();
  } catch (SQLException e1) {
  e1.printStackTrace();
  }
 }finally{
  try {
  con.setAutoCommit(true);
  con.close();
  } catch (SQLException e) {
  e.printStackTrace();
  }
 }
 return returnObj;
 }

}

대리 2:강 전 은 필요 없 지만 모든 것 을 대리 합 니 다.

package cn.hncu.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class TxProxy2 implements InvocationHandler {

 private Object srcObj=null;

 private TxProxy2(Object srcObj) {
 this.srcObj = srcObj;
 }


 public static<T> T getProxy(Class<T> c){
 Object obj=null;
 try {
  obj = c.newInstance();
 } catch (Exception e) {
  e.printStackTrace();
 }
 Object newObj=Proxy.newProxyInstance(
  TxProxy2.class.getClassLoader(), 
  c.getInterfaces(), 
  new TxProxy2(obj));
 return (T) newObj;
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
 Connection con=null;
 Object returnObj=null;
 try {
  con=ConnUtils5.getConnection();
  System.out.println("invoke      :"+con);
  con.setAutoCommit(false);

  returnObj=method.invoke(srcObj, args);

  System.out.println("      ...");
  con.commit();
 } catch (Exception e) {
  try {
  System.out.println("      ...");
  con.rollback();
  } catch (SQLException e1) {
  e1.printStackTrace();
  }
 }finally{
  try {
  con.setAutoCommit(true);
  con.close();
  } catch (SQLException e) {
  e.printStackTrace();
  }
 }
 return returnObj;
 }

}

주해

package cn.hncu.utils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value=ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Transaction {

}

대리 3:주석 으로 필요 한 사 무 를 실현 하려 면 사무 로 합 니 다.

package cn.hncu.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class TxProxy3 implements InvocationHandler {

 private Object srcObj=null;

 private TxProxy3(Object srcObj) {
 this.srcObj = srcObj;
 }


 public static<T> T getProxy(T srcObj){
 Object newObj=Proxy.newProxyInstance(
  TxProxy3.class.getClassLoader(), 
  srcObj.getClass().getInterfaces(), 
  new TxProxy3(srcObj));
 return (T) newObj;
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
 /*                
 if(method.getName().equals("close")){
  ...  
 }else{
  return method.invoke(srcObj, args);
 }
 */
 if(method.isAnnotationPresent(Transaction.class)){

  Connection con=null;
  Object returnObj=null;
  try {
  con=ConnUtils5.getConnection();
  System.out.println("invoke      :"+con);
  con.setAutoCommit(false);
  //       ,  
  returnObj=method.invoke(srcObj, args);

  System.out.println("      ...");
  con.commit();
  } catch (Exception e) {
  try {
   System.out.println("      ...");
   con.rollback();
  } catch (SQLException e1) {
   e1.printStackTrace();
  }
  }finally{
  try {
   con.setAutoCommit(true);
   con.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
  return returnObj;
 }else{
  System.out.println("       ,    !");
  return method.invoke(srcObj, args);
 }
 }

}

자원 파일 jdbc.properties

##MySQL
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/hncu?useUnicode=true&characterEncoding=utf-8
username=root
password=1234
size=3
##Oracle
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#username=scott
#password=tiger

stud 층 의 servlet 층 CQuery Servlet.자바

package cn.hncu.stud.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.Book;
import cn.hncu.domain.Stud;
import cn.hncu.stud.service.IStudService;
import cn.hncu.stud.service.StudServiceImpl;
import cn.hncu.utils.TxProxy3;

public class QueryServlet extends HttpServlet {

 //  
 //1.
// IStudService service=(IStudService) TxProxy.getProxy(new StudServiceImpl());
 //2.
// IStudService service=TxProxy2.getProxy(StudServiceImpl.class);
 //3.
 IStudService service=TxProxy3.getProxy(new StudServiceImpl());
 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

 doPost(request, response);
 }


 public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 String cmd=request.getParameter("cmd");
 System.out.println("cmd:"+cmd);
 if("query".equals(cmd)){
  query(request, response);
 }else if("add".equals(cmd)){
  add(request, response);
 }
 }


 public void query(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 System.out.println("service:"+service);
 List<Map<String, String>> studs=service.query();
 request.setAttribute("studs", studs);
 request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
 }
 public void add(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 //1     2    (id    dao   )
 String name[]=request.getParameterValues("name");
 Stud s=new Stud();
 s.setName(name[0]);
 //    
 String books[]=request.getParameterValues("book");
 //     ---          ,       
 if(books==null||books.length<=0){
  return;
 }
 String prices[]=request.getParameterValues("price");
 for(int i=0;i<books.length;i++){
  Book b=new Book();
  b.setName(books[i]);
  b.setPrice(Double.parseDouble(prices[i]));
  //※        “   ”       
  s.getBooks().add(b);//  
  b.setS(s);//  
 }
 //3  service 
 try {
  service.save(s);
 } catch (Exception e) {
  //      
 }

 }

}

stud 층 의 service 층 C
인터페이스:

package cn.hncu.stud.service;

import java.util.List;
import java.util.Map;

import cn.hncu.domain.Stud;
import cn.hncu.utils.Transaction;



public interface IStudService {

 public List<Map<String, String>> query();

 //  ,           ,,,,           (        )
 @Transaction
 public void save(Stud stud) throws Exception ;
}

실현 류

package cn.hncu.stud.service;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.hncu.domain.Stud;
import cn.hncu.stud.dao.BookDAO;
import cn.hncu.stud.dao.BookJdbcDao;
import cn.hncu.stud.dao.StudDAO;
import cn.hncu.stud.dao.StudJdbcDAO;
import cn.hncu.utils.ConnUtils5;

/*               dao       ,             dao,
 *           ,       ,     !
 * 
 *        :
 * 1、      dao,      sql        ,      
 * 2、    service    dao,        。
 */
public class StudServiceImpl implements IStudService {

 //  
 StudDAO dao_stud=new StudJdbcDAO();
 BookDAO dao_book=new BookJdbcDao();
 @Override
 public List<Map<String, String>> query() {
 return dao_stud.query();
 }
 @Override
 public void save(Stud stud) throws Exception {
 dao_stud.save(stud);
 dao_book.save(stud.getBooks());
 }

}

stud 층 의 dao 층 C
Stud 인터페이스 C 분리 식 방법,하나의 표 는 하나의 dao 에 대응 하여 프레임 을 준비 합 니 다.

package cn.hncu.stud.dao;

import java.util.List;
import java.util.Map;

import cn.hncu.domain.Stud;

public interface StudDAO {

 public List<Map<String, String>> query();
 public void save(Stud stud) throws Exception;
}

Stud 구현 클래스

package cn.hncu.stud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.hncu.domain.Book;
import cn.hncu.domain.Stud;
import cn.hncu.utils.ConnUtils3;

public class StudJdbcDAO implements StudDAO {

 @Override
 public List<Map<String, String>> query() {
 List<Map<String, String>> list=new ArrayList<Map<String,String>>();
 //  map      , List<Map>       
 Connection con=null;
 try {
  con=ConnUtils3.getConnection();
  Statement st=con.createStatement();
  String sql="select * from stud";
  ResultSet rs=st.executeQuery(sql);
  while(rs.next()){
  Map<String,String> m=new HashMap<String, String>();
  m.put("id", (String) rs.getObject(1));
  m.put("name", (String) rs.getObject(2));
  list.add(m);
  }
  rs.close();
  st.close();
 } catch (SQLException e) {
  e.printStackTrace();
 }finally{
  try {
  con.close();
  } catch (SQLException e) {
  e.printStackTrace();
  }
 }


 return list;
 }

 @Override
 public void save(Stud stud) throws Exception {
 Connection con=ConnUtils3.getConnection();
 System.out.println("      :"+con);
 String sql="insert into stud values(?,?)";
 String uuid=UUID.randomUUID().toString().replace("-", "");
 PreparedStatement pst=con.prepareStatement(sql);
 stud.setId(uuid);//  "  " book    "  " id,    
 pst.setString(1, uuid);
 pst.setString(2, stud.getName());
 System.out.println("1:"+uuid+",2:"+stud.getName());
 pst.executeUpdate();
// con.close();//     con,        
 }

}

북 인터페이스

package cn.hncu.stud.dao;

import java.util.List;

import cn.hncu.domain.Book;

public interface BookDAO {

 public void save(List<Book> books) throws Exception;
}

도서 실현 클래스

package cn.hncu.stud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import cn.hncu.domain.Book;
import cn.hncu.utils.ConnUtils3;

public class BookJdbcDao implements BookDAO {

 @Override
 public void save(List<Book> books) throws Exception {
 Connection con=ConnUtils3.getConnection();
 System.out.println("      :"+con);
 String sql="insert into book(name,price,studid) values(?,?,?)";
 PreparedStatement pst=con.prepareStatement(sql);
 for(Book b:books){
  pst.setString(1, b.getName());
  pst.setDouble(2, b.getPrice());
  pst.setObject(3, "12132312");//  (             ,       )--     
//  pst.setObject(3, b.getS().getId());
  System.out.println("1:"+b.getName()+",2:"+b.getPrice()+",3:"+b.getS().getId());
  pst.addBatch();//      
 }
 pst.executeBatch();//     

// con.close();//       con,      

 }

}

값 개체
스 터 드 대상

package cn.hncu.domain;

import java.util.ArrayList;
import java.util.List;
/*
 *       “ ”        
 */
public class Stud {

 private String id;
 private String name;
 //※  “ ”       ---      “     ”
 private List<Book> books=new ArrayList<Book>();//  ,            new  。
 public String getId() {
 return id;
 }
 public void setId(String id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }



 public List<Book> getBooks() {
 return books;
 }
 public void setBooks(List<Book> books) {
 this.books = books;
 }
 @Override
 public String toString() {
 return "id=" + id + "," + name + "," + books;
 }

}

도서 대상

package cn.hncu.domain;
/*
 *       “ ”        
 */
public class Book {

 private Integer id;
 //               ,            ---         (             )
 private String name;
 private Double price;
 //※  “ ”            (  ,  studid)---      “     ”
 private Stud s;//    
 //private String studid;//★★     
 public Integer getId() {
 return id;
 }
 public void setId(Integer id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public Double getPrice() {
 return price;
 }
 public void setPrice(Double price) {
 this.price = price;
 }
 public Stud getS() {
 return s;
 }
 public void setS(Stud s) {
 this.s = s;
 }
 /*
 *       toString()         ,         ,              ,      !
 */
 @Override
 public String toString() {
 return "id=" + id + "," + name + "," + price;//      Stud  ,      
 }

}

학생 정보 페이지 표시 jsps/show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <head>

 <title>      </title>
 </head>

 <body>
 <h2>    </h2>
 <c:forEach items="${studs}" var="x">
 ${x.id},${x.name}<br/>
 </c:forEach>
 </body>
</html>
효과 그림:

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기