Java Web Learning server development process
Package com. product. dbutil. register. action; Control Layer
Package com. product. dbutil. register. service; service layer
Package com. product. dbutil. register. dao; data access layer.
Definition code of the control layer:
Package com. product. dbutil. register. action; import java. io. IOException; import java. io. printWriter; import java. util. arrayList; import java. util. list; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. product. dbutil. register. dao. registerDao; import com. product. dbutil. register. service. registerService; import com.sun.org. apache. bcel. internal. generic. ARRAYLENGTH; public class RegisterAction extends HttpServlet {private RegisterService service; // service layer interface/*** Constructor of the object. */public RegisterAction () {super ();}/*** Destruction of the servlet.
*/Public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet.
** This method is called when a form has its tag value method equals to get. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {this. doPost (request, response); // rewrite doPost method}/*** The doPost method of the servlet.
** This method is called when a form has its tag value method equals to * post. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occurred */public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {String path = request. getContextPath (); // used to redirect response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); String username = request. getParameter ("username"); String pswd = request. getParameter ("pswd"); String realname = request. getParameter ("realname"); ListParams = new ArrayList(); Params. add (username); params. add (pswd); params. add (realname); boolean flag = service. registerUser (params); if (flag) {response. sendRedirect (path + "/index. jsp "); // redirection Implementation} out. flush (); out. close ();}/*** Initialization of the servlet.
** @ Throws ServletException * if an error occurs */public void init () throws ServletException {// Put your code hereservice = new RegisterDao ();}}
Service layer, which defines business logic processing specifications. The Code is as follows:
Package com. product. dbutil. register. service; import java. util. List; public interface RegisterService {// complete the public boolean registerUser (ListParams );}
Access the database at the data access layer:Package com. product. dbutil. register. dao; import java. util. list; import com. product. dbutil. jdbc. jdbcUtils; import com. product. dbutil. register. service. registerService; public class RegisterDao implements RegisterService {private JdbcUtils utils = null; public RegisterDao () {// operation database utils = new JdbcUtils ();} /** completed the preparation of user-registered dao ** @ see * com. product. dbutil. register. service. registerService # registerUser (java *. util. list) */public boolean registerUser (ListParams) {// TODO Auto-generated method stubboolean flag = false; String SQL = "insert into userinfo (username, pswd, realname) values (?,?,?) "; Try {// obtain the link utils first. getConnection (); flag = utils. updateByPreparedStatement (SQL, params); System. out. println ("-flag -->" + flag);} catch (Exception e) {e. printStackTrace (); // TODO: handle exception} finally {// shut down the database link utils. releaseConn () ;}return flag ;}}
Database tools:
Package com. product. dbutil. jdbc; import java. lang. reflect. field; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. resultSetMetaData; import java. SQL. SQLException; import java. SQL. statement; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; public class JdbcUtils {// indicates the user who defines the database Name: private final String USERNAME = "root"; // defines the Database PASSWORD private final String PASSWORD = "admin"; // defines the database DRIVER information private final String DRIVER = "com. mysql. jdbc. driver "; // defines the address for accessing the database private final String URL =" jdbc: mysql: // localhost: 3306/mydb "; // defines the Connection of the database private connection Connection; // define the execution object private PreparedStatement pstmt of the SQL Statement; // define the returned result set private ResultSet resultSet; // implement the batch processing function private Statement stmt; p Ublic JdbcUtils () {try {Class. forName (DRIVER); System. out. println ("the DRIVER has been registered !! ");} Catch (Exception e) {// TODO: handle exception} // defines the Connection to obtain the database public connection getConnection () {try {Connection = DriverManager. getConnection (URL, USERNAME, PASSWORD);} catch (Exception e) {// TODO: handle exception} return connection;} public boolean deleteByBatch (String [] SQL) throws SQLException {boolean flag = false; stmt = connection. createStatement (); if (SQL! = Null) {for (int I = 0; I
Params) throws SQLException {boolean flag = false; int result =-1; // indicates the number of rows affected by the database when the user adds, deletes, and modifies the database. pstmt = connection. prepareStatement (SQL); int index = 1; if (params! = Null &&! Params. isEmpty () {for (int I = 0; I <params. size (); I ++) {pstmt. setObject (index ++, params. get (I) ;}} result = pstmt.exe cuteUpdate (); flag = result> 0? True: false; return flag;}/*** query returns a single record ** @ param SQL * @ param params * @ return * @ throws SQLException */public Map
FindSimpleResult (String SQL, List
Params) throws SQLException {Map
Map = new HashMap
(); Int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I <params. size (); I ++) {pstmt. setObject (index ++, params. get (I) ;}} resultSet = pstmt.exe cuteQuery (); // return the query result ResultSetMetaData metaData = resultSet. getMetaData (); int col_len = metaData. getColumnCount (); // get the column name while (resultSet. next () {for (int I = 0; I <col_len; I ++) {String cols_name = metaData. getColumnName (I + 1); Object cols_value = resultSet. getObject (cols_name); if (cols_value = null) {cols_value = "";} map. put (cols_name, cols_value) ;}} return map ;} /*** query returns multiple rows of records ** @ param SQL * @ param params * @ return * @ throws SQLException */public List
> FindMoreResult (String SQL, List
Params) throws SQLException {List
> List = new ArrayList
> (); Int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I <params. size (); I ++) {pstmt. setObject (index ++, params. get (I) ;}} resultSet = pstmt.exe cuteQuery (); ResultSetMetaData metaData = resultSet. getMetaData (); int cols_len = metaData. getColumnCount (); while (resultSet. next () {Map
Map = new HashMap
(); For (int I = 0; I <cols_len; I ++) {String cols_name = metaData. getColumnName (I + 1); Object cols_value = resultSet. getObject (cols_name); if (cols_value = null) {cols_value = "";} map. put (cols_name, cols_value);} list. add (map) ;}return list ;}// the jdbc encapsulation can be encapsulated by the reflection mechanism: public
T findSimpleRefResult (String SQL, List
Params, Class
Cls) throws Exception {T resultObject = null; int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I <params. size (); I ++) {pstmt. setObject (index ++, params. get (I) ;}} resultSet = pstmt.exe cuteQuery (); ResultSetMetaData metaData = resultSet. getMetaData (); int cols_len = metaData. getColumnCount (); while (resultSet. next () {// use the reflection mechanism to create an instance resultObject = cls. newInstance (); for (int I = 0; I <cols_len; I ++) {String cols_name = metaData. getColumnName (I + 1); Object cols_value = resultSet. getObject (cols_name); if (cols_value = null) {cols_value = "";} Field field = cls. getDeclaredField (cols_name); field. setAccessible (true); // open the private permission field for accessing javabean. set (resultObject, cols_value) ;}return resultObject;}/*** access the database through reflection ** @ param
* @ Param SQL * @ param params * @ param cls * @ return * @ throws Exception */public
List
FindMoreRefResult (String SQL, List
Params, Class
Cls) throws Exception {List
List = new ArrayList
(); Int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I <params. size (); I ++) {pstmt. setObject (index ++, params. get (I) ;}} resultSet = pstmt.exe cuteQuery (); ResultSetMetaData metaData = resultSet. getMetaData (); int cols_len = metaData. getColumnCount (); while (resultSet. next () {T resultObject = cls. newInstance (); for (int I = 0; I <cols_len; I ++) {String cols_name = metaData. getColumnName (I + 1); Object cols_value = result Set. getObject (cols_name); if (cols_value = null) {cols_value = "";} Field field = cls. getDeclaredField (cols_name); field. setAccessible (true); field. set (resultObject, cols_value);} list. add (resultObject);} return list;} public void releaseConn () {if (resultSet! = Null) {try {resultSet. close ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} if (stmt! = Null) {try {stmt. close ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} if (pstmt! = Null) {try {pstmt. close ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} if (connection! = Null) {try {connection. close () ;}catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}
The control layer calls the service layer. The service layer calls the dao layer.