Java Student Information Management system design _java

Source: Internet
Author: User
Tags commit int size rollback uuid wrapper

The student information for this example adds transactions to the database (you can commit the transaction, rollback the transaction, and use local thread refinement)

Main Page index.jsp

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

Get a database connection tool Connutils5.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 {//local thread management object, for implementation: the connection obtained by the same thread is the same private static threadlocal< connection> t=new Threadloc
 Al<connection> ();
 Private final static list<connection> pool=new arraylist<connection> ();
 private static int size;//is read by the resource file private ConnUtils5 () {} static{Properties P=new properties (); try {//The following method can read a resource file under Classpath in a pure Java project, but cannot read the Java EE project.
Because Tomcat changed the system's default class loader to//p.load (Classloader.getsystemclassloader (). Getsystemresourceasstream ("jdbc.properties"));

  P.load (Classloader.getsystemresourceasstream ("jdbc.properties")); Read the resource file under the classpath of the Web project, which can be 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); Change the Conn.close () method//Use proxy mode to generate an enhanced version of the Conn object, and its close () method to intercept the object Ncon=proxy.newproxyinstance (ConnUtils3.class.ge Tclassloader (),//Conn.getclass (). Getinterfaces (),//later this method is not possible, should be the implementation class in the driver and our current program is not in the same space (ClassLoader different) new Class[]{con  Nection.class}, new Invocationhandler () {@Override public object Invoke (Object Proxy, Method method, object[] args) throws Throwable {if (Method.getname (). Equals ("Close")) {System.out.println ("Return a Link:" + (Connection) pro
     XY);
     Pool.add ((Connection) proxy);
    return null;
    Return Method.invoke (con, args);
  }
  });
  Pool.add ((Connection) ncon); Catch (Exception e)
 {E.printstacktrace ();
 The public static synchronized Connection getconnection () {//is taken first from T, if any, take it out if it is not taken in the pool and put the object in T Connection con=t.get ();
  if (con==null) {if (Pool.size () <=0) {System.out.println ("The pool is disconnected ...");
  try {thread.sleep (1000);
  catch (Interruptedexception e) {e.printstacktrace ();
  return getconnection ();
  } con=pool.remove (0);

 T.set (con);//Put into T} return con;//take one Move one}}

Resource File 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

Value Object
Stud.java

Package cn.hncu.domain;

Import java.util.ArrayList;
Import java.util.List;
 * * * a One-to-many "one" side value object of the building method
 * * Public
class Stud {

 private String ID;
 private String name;
 ※ specifically for "many" side to add a set---embodies the "one-to-many relationship" in multiple tables
 private list<book> books=new arraylist<book> ();/Note that The collection is to be new when it is constructed or before. 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;
 }

}

Book.java

Package cn.hncu.domain;
 * * * the "multi" square value object of the construction method * * Public
class Book {

 private Integer ID;
 The base data types are all declared with the wrapper class, ready to use the framework for later---wrapper classes can be compatible with the framework (because the generic framework uses class reflection)
 private String name;
 Private Double Price;
 ※ for "One" side to add a variable of the object type (note, do not studid)---embodies the "one-to-many relationship" in multiple tables
 private Stud s;//set owner
 //private String studid;// ★ Don't do this
 . Set 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;
 }
 * * * Multiple Table association when the ToString () method to pay attention to a trap, is one side of the output of the other side, while the other side and in turn output the previous side, the formation of infinite recursion!
 * *
 @Override public
 String toString () {return
 "id= + ID +", "+ Name +", "+ price;//cannot output stud object here, no Then infinite recursion
 }

}

Stud layer of the servlet layer –queryservlet.java

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;
 public class Queryservlet extends HttpServlet {//injection istudservice service=new Studserviceimpl (); public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoP
 OST (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 {list<map<st
 Ring, 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
 Collect parameter 2 organization parameters (the ID field is left in DAO to complement) String name[]=request.getparametervalues ("name");
 System.out.println (Name[0]);
 Stud s=new Stud ();
 S.setname (Name[0]);
 Library information String books[]=request.getparametervalues ("book"); Protection---Price protection should also be written, here we are lazy 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));
 ※ completes the "one-to-many" relationship of two value objects Data Encapsulation S.getbooks (). Add (b);//One b.sets (s);//Multiparty}//3 invokes service layer try {service.save (s); catch (exception e) {//Guide failed Page}}}

 

The service layer of the stud layer –
Interface:

Package cn.hncu.stud.service;

Import java.util.List;
Import Java.util.Map;

Import Cn.hncu.domain.Stud;

Public interface Istudservice {public

 list<map<string, string>> query ();
 public void Save (Stud Stud);
}

Implementation class

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.CONNUTILS3;
 * * We will usually use a DAO standalone operation in the future development of a table, there are several entity tables in the system to write a few DAO, * after the framework is so dry, we have to do so, because the structure is good!
 * * In the case of transactions: * 1, if there is only one DAO, but to execute multiple SQL statements and involve additions and deletions, then open transaction * 2, if a service calls multiple DAO, usually also open transaction.
 * * Public class Studserviceimpl implements Istudservice {//injection 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) {Connection con=null;
  try {con=connutils3.getconnection ();
  System.out.println ("Get a Link:" +con);
  Con.setautocommit (FALSE);
  Dao_stud.save (stud);

  Dao_book.save (Stud.getbooks ()); System.out.println ("Submit a transaction ...")");
 Con.commit ();
  catch (Exception e) {try {System.out.println ("Roll back a transaction ...");
  Con.rollback ();
  catch (SQLException E1) {e1.printstacktrace ();
  }finally{try {con.setautocommit (true);
  Con.close ();
  catch (SQLException e) {e.printstacktrace ();

 }
 }
 }

}

The DAO layer of the Stud layer –
Stud interface

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 Implementation Class

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&LT ;
 Map<string, string>> list=new arraylist<map<string,string>> ();
 A Map is a row of data, list<map> is the entire data table 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 ("Get a Link:" +con);
 String sql= "INSERT into stud values (?,?)";
 String Uuid=uuid.randomuuid (). toString (). Replace ("-", "");
 PreparedStatement pst=con.preparestatement (SQL);
 Stud.setid (UUID)//for "multi-party" that book can get "one side" of the ID, specialized complement pst.setstring (1, UUID);
 Pst.setstring (2, Stud.getname ());
 System.out.println ("1:" +uuid+ ", 2:" +stud.getname ());
Pst.executeupdate ();

 Con.close ()//Get the same con, there's no need to turn it off}}

Book Interface

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;
}

Book Implementation class

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 ("Get a Link:" +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");//exception (intentionally to a nonexistent foreign key field to test transaction rollback)--Measure transaction rollback
//  Pst.setobject (3, B.gets (). GetId ());
  System.out.println ("1:" +b.getname () + ", 2:" +b.getprice () + ", 3:" +b.gets (). GetId ());
  Pst.addbatch (),//Add to Batch
 }
 Pst.executebatch ()//Execute batch

//Con.close ();//Here's the same con, there's no need to close

 }

}

Show Student Information page jsps/show.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib
"uri=" http:// Java.sun.com/jsp/jstl/core "prefix=" C "%>
 
 

Effect Chart:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.