Java integrated easyui for addition, deletion, and modification operations, java integrated easyui for addition, deletion

Source: Internet
Author: User
Tags mysql gui

Java integrated easyui for addition, deletion, and modification operations, java integrated easyui for addition, deletion

First, send it.

Show all user information

Add User Information

Delete user information

Edit user information

Next we will introduce the crud of easyui and how to exchange it with the background in java.

The frontend HTML page is named crud1.html.

1. First, it is a datagrid marked by class,

The official explanation for the url is as follows: To load data from remote server, you should set 'url' peoperty, where server will return JSON format data

The second is pagination. Its official explanation is

Set 'pagination' property to true, which will generate a pagination bar on datagrid bottom. The pagination will send two parameters to server:
  • Page: The page number, start with 1.
  • Rows: The page rows per page.

The official explanation of thread is that the datagrid columns is defined in <thead> markup (the columns of the datagrid are defined in the <thread> mark)

2. Toolbar

About the toolbar, We don't need to write any javascript code, attach a toolbar to the datagrid via 'toolbar' attribute.

In the toolbar, you can call the onclick method written during definition.

3. methods defined in the toolbar

The method is in js, for example, newUser.

Click "Add User" in the toolbar to call the newUser () method in js.

(1) Open the dialog box with the id of dlg and set the title of the dialog box to "Add User"

$ ("# Dlg"). dialog ('open'). dialog ('settitle', 'add user ');
(2) The definition of the dialog box is defined in the body as follows.

<Div id = "dlg" class = "easyui-dialog" style = "width: 400px; height: 250px; padding: 10px 20px "closed =" true "buttons =" # dlg-buttons "> <form id =" fm "method =" post "> <table cellspacing =" 10px; "> <tr> <td> Name: </td> <input name = "name" class = "easyui-validatebox" required = "true" style = "width: 200px; "> </td> </tr> <td> contact number: </td> <input name = "phone" class = "easyui-validatebox" required = "true" style = "width: 200px; "> </td> </tr> <td> Email: </td> <input name = "email" class = "easyui-validatebox" validType = "email" required = "true" style = "width: 200px; "> </td> </tr> <td> QQ: </td> <input name = "qq" class = "easyui-validatebox" required = "true" style = "width: 200px; "> </td> </tr> </table> </form> </div> <div id =" dlg-buttons "> <a href =" javascript: void (0) "class =" easyui-linkbutton "iconCls =" icon-OK "onclick =" saveUser () "> Save </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "iconCls =" icon-cancel "onclick =" javascript: $ ('# dlg '). dialog ('close') "> close </a> </div>
(3) Clear the content of the dialog box

$('#fm').form('clear');
(4) Interaction with the background java program through ajax

url='userSave';

The background java program is like this.

Accept the four values passed in by the user, complete database operations, and then put the return value of the result into a jsonObject.

Public class UserSaveServlet extends HttpServlet {/*****/private static final long serialVersionUID = 1L; DbUtil dbUtil = new DbUtil (); UserDao userDao = new UserDao (); @ Overrideprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response) ;}@ Overrideprotected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); String name = request. getParameter ("name"); String phone = request. getParameter ("phone"); String email = request. getParameter ("email"); String qq = request. getParameter ("qq"); String id = request. getParameter ("id"); User user = new User (name, phone, email, qq); if (StringUtil. isNotEmpty (id) {user. setId (Integer. parseInt (id);} Connection con = null; try {int saveNums = 0; con = dbUtil. getCon (); JSONObject result = new JSONObject (); if (StringUtil. isNotEmpty (id) {saveNums = userDao. userModify (con, user);} else {saveNums = userDao. userAdd (con, user);} if (saveNums = 1) {result. put ("success", "true");} else {result. put ("success", "true"); result. put ("errorMsg", "saved successfully");} ResponseUtil. write (response, result);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {try {dbUtil. closeCon (con);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
Well, the above is the complete interaction process between easyui and the background java program.

The complete code is provided below:

Project Structure:

Database Table creation statement: A t_user table

/* SQLyog Enterprise Edition-MySQL GUI v8.14 MySQL-5.1.49-community: database-db_easyui ************************************* *********************************//*! 40101 set names utf8 */;/*! 40101 SET SQL _MODE = ''*/;/*! 40014 SET @ OLD_UNIQUE_CHECKS = @ UNIQUE_CHECKS, UNIQUE_CHECKS = 0 */;/*! 40014 SET @ OLD_FOREIGN_KEY_CHECKS = @ FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0 */;/*! 40101 SET @ OLD_ SQL _MODE = @ SQL _MODE, SQL _MODE = 'no _ AUTO_VALUE_ON_ZERO '*/;/*! 40111 SET @ OLD_ SQL _NOTES = SQL _notes, SQL _NOTES = 0 */; CREATE DATABASE /*! 32312 if not exists */'db _ easyui '/*! 40100 default character set utf8 */; USE 'db _ easyui ';/* Table structure for table 't_ user' */drop table if exists 't_ user '; create table 't_user' ('id' int (11) not null AUTO_INCREMENT, 'name' varchar (20) default null, 'phone' varchar (20) default null, 'email 'varchar (20) default null, 'qq' varchar (20) default null, primary key ('id') ENGINE = InnoDB AUTO_INCREMENT = 21 default charset = utf8; /* Data for the table 't_ user '*/

Front-end page crud1.html

<Html> Model layer encapsulation of the user table and pageBean
Public class PageBean {private int page; // page number of private int rows; // The number of records on each page private int start; // The start page // The get and set methods are omitted}
Public class User {private int id; private String name; private String phone; private String email; private String qq; public User () {} public User (String name, String phone, string email, String qq) {this. name = name; this. phone = phone; this. email = email; this. qq = qq;} // omit the get and set Methods}

Tool class:

(1) database connection class

public class DbUtil {private String dbUrl="jdbc:mysql://localhost:3306/db_easyui";private String dbUserName="root";private String dbPassword="root";private String jdbcName="com.mysql.jdbc.Driver";public Connection getCon()throws Exception{Class.forName(jdbcName);Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);return con;}public void closeCon(Connection con)throws Exception{if(con!=null){con.close();}}}
(2) convert the result to the public class JsonUtil of the json array tool {/*** convert the result set to the json array format * @ param rs * @ return * @ throws Exception */public static JSONArray formatRsToJsonArray (ResultSet rs) throws Exception {ResultSetMetaData md = rs. getMetaData (); int num = md. getColumnCount (); JSONArray array = new JSONArray (); while (rs. next () {JSONObject mapOfColValues = new JSONObject (); for (int I = 1; I <= num; I ++) {mapOfColValues. put (md. getColumnName (I), rs. getObject (I);} array. add (mapOfColValues) ;}return array ;}}
(3) class of information output to the page

public class ResponseUtil {public static void write(HttpServletResponse response,Object o)throws Exception{response.setContentType("text/html;charset=utf-8");PrintWriter out=response.getWriter();out.print(o.toString());out.flush();out.close();}}

Below is the control layer controller

Delete the controller of user information

Public class UserDeleteServlet extends HttpServlet {/*****/private static final long serialVersionUID = 1L; DbUtil dbUtil = new DbUtil (); UserDao userDao = new UserDao (); @ Overrideprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response) ;}@ Overrideprotected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// String delId = request. getParameter ("delId"); String delId = request. getParameter ("delId"); Connection con = null; try {con = dbUtil. getCon (); JSONObject result = new JSONObject (); int delNums = userDao. userDelete (con, delId); if (delNums = 1) {result. put ("success", "true");} else {result. put ("errorMsg", "failed to delete");} ResponseUtil. write (response, result);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {try {dbUtil. closeCon (con);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}
Controller that displays user information

public class UserListServlet extends HttpServlet{/** *  */private static final long serialVersionUID = 1L;DbUtil dbUtil=new DbUtil();UserDao userDao=new UserDao();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String page=request.getParameter("page");String rows=request.getParameter("rows");PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));Connection con=null;try {con=dbUtil.getCon();JSONObject result=new JSONObject();JSONArray jsonArray=JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean));int total=userDao.userCount(con);result.put("rows", jsonArray);result.put("total", total);ResponseUtil.write(response, result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {dbUtil.closeCon(con);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
Controller that saves user information

Public class UserSaveServlet extends HttpServlet {/*****/private static final long serialVersionUID = 1L; DbUtil dbUtil = new DbUtil (); UserDao userDao = new UserDao (); @ Overrideprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response) ;}@ Overrideprotected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); String name = request. getParameter ("name"); String phone = request. getParameter ("phone"); String email = request. getParameter ("email"); String qq = request. getParameter ("qq"); String id = request. getParameter ("id"); User user = new User (name, phone, email, qq); if (StringUtil. isNotEmpty (id) {user. setId (Integer. parseInt (id);} Connection con = null; try {int saveNums = 0; con = dbUtil. getCon (); JSONObject result = new JSONObject (); if (StringUtil. isNotEmpty (id) {saveNums = userDao. userModify (con, user);} else {saveNums = userDao. userAdd (con, user);} if (saveNums = 1) {result. put ("success", "true");} else {result. put ("success", "true"); result. put ("errorMsg", "saved successfully");} ResponseUtil. write (response, result);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {try {dbUtil. closeCon (con);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

The configuration file web. xml is attached.

<servlet>  <servlet-name>userListServlet</servlet-name>  <servlet-class>com.qzp.web.UserListServlet</servlet-class>  </servlet>    <servlet>  <servlet-name>userDeleteServlet</servlet-name>  <servlet-class>com.qzp.web.UserDeleteServlet</servlet-class>  </servlet>    <servlet>  <servlet-name>userSaveServlet</servlet-name>  <servlet-class>com.qzp.web.UserSaveServlet</servlet-class>  </servlet>    <servlet-mapping>  <servlet-name>userListServlet</servlet-name>  <url-pattern>/userList</url-pattern>  </servlet-mapping>    <servlet-mapping>  <servlet-name>userDeleteServlet</servlet-name>  <url-pattern>/userDelete</url-pattern>  </servlet-mapping>    <servlet-mapping>  <servlet-name>userSaveServlet</servlet-name>  <url-pattern>/userSave</url-pattern>  </servlet-mapping>


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.