IntelliJ IDEA Develops Web Application Program to Realize Data Addition, Deletion, Check and Change

Posted by aissa on Sun, 30 Jun 2019 01:30:15 +0200

This paper is divided into two parts:
1. Intellij Idea creates Web applications;
2. Develop a WEB application with additions, deletions and modifications and deploy it to the local server.

    Raw materials:
        Intellij IDE
        JDK
        Tomcat
        Mysql
        Navicat for MySQL
        Browser
        Develop related jar packages (c3p0, commons-beanutils, commons-collections, commons-dbutils, commons-logging, jstl, mchange-commons-java, mysql-connector-java)

New Construction and Configuration Project

File - > New Project - > Enter the project name "Demos" and select Project SDK as 1.7 - > Next - > Finish.

In the mouse click on the item name demos - > right-click on New and select Module - >.
Enter Module name "first web" - > Click Next - >.
Check "Web Application" - > Confirm that "Create web.xml" - > Finish has been checked.

Create two folders under web/WEB-INF: classes and lib, classes are used to store the class files output after compilation, and lib is used to store third-party jar packages.

Configure folder paths
File - > Project Structure (shortcut key: Ctrl + Shift + Alt + S) - > Select Module:
Select Paths - > Select "Use module compile output path" - > Select both Output path and Test output path to select the classes folder you just created.
Next, select Dependencies - > and select Module SDK as 1.7 - > click the "+" number on the right - > select 1 "Jars or Directories"
-> Select the lib folder you just created - > select "jar directory" - > and then go back to OK.

Open the menu Run - > Select Edit Configuration - >.
Click on the "+" number - > Select "Tomcat Server" - > Select "Local" - >.
Enter a new service name at "Name" and click "Configure..." after "Application server" To pop up the Tomcat Server window, select the locally installed Tomcat Directory - > OK

In the "Server" palette of the "Run/Debug Configurations" window, uncheck the "After launch", set the "HTTP port" and "JMX port" (default), click Apply - > OK, and the Tomcat configuration is complete.

Deploy and run the project in Tomcat
Run - > Edit Configurations, enter the "Run/Debug Configurations" window - > Select the Tomcat container you just created - > Select Deployment - > Click the "+" number on the right - > Select Artifact.

Select the web project - > Application context to fill in "/ hello"> OK (this hello can be replaced by the name you want, which is the program root directory when the browser accesses, / representing the tomcat server root directory).

Implementing Adding Users

Now that we're ready, we're starting to write code:

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>homepage</title>
</head>
<frameset rows="20%,*">
    <frame src="<c:url value='/top.jsp'/>" name="top"/>
    <frame src="<c:url value='/welcome.jsp'/>" name="main"/>
</frameset>
</html>

index contains top.jsp. For easy operation, top.jsp is used to interact with users, while welcom is responsible for data display. By default, well has no data, and name = "main" means that the main page is the framework.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <!-- His function is to specify a framework for displaying content for all forms and hyperlinks on this page.-->
    <base target="main">
    <title>My JSP 'top.jsp' starting page</title>
</head>
<body style="text-align: center;">
    <h1>Customer relationship management system</h1>
    <a href="<c:url value='/add.jsp'/>">Adding Customers</a>
    <a href="<c:url value='/CustomerServlet?method=findAll'/>">Search for customers</a>
    <a href="<c:url value='/query.jsp'/>">Advanced Search</a>

</body>
</html>

welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>

We see that there are three operations in the early top.jsp: adding users, querying users, advanced search. We start with adding users, because there is no data in the database at the beginning. c:url is a jstl expression, where most inconveniences occur. Click Add to jump to add.jsp

add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3 align="center">Adding Customers</h3>

<form action="<c:url value='/CustomerServlet'/>" method="post">
    <input type="hidden" name="method" value="add">
    <table border="1" align="center" width="40%" style="margin-left: 100px">
        <tr>
            <td width="100px">Customer Name</td>
            <td width="40%">
                <input type="text" name="name"/>
            </td>
            <td align="left">
                <label id="nameError" class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td>Client Gender</td>
            <td>
                <input type="radio" name="gender" value="male" id="male"/>
                <label for="male">male</label>
                <input type="radio" name="gender" value="female" id="female"/>
                <label for="female">female</label>
            </td>
            <td>
                <label id="genderError" class="error">&nbsp;</label>
            </td>
        </tr>
       <tr>
           <td>Mobile phone</td>
           <td>
               <input type="text" name="phone" id="phone">
           </td>
           <td>
              <label id="phoneError" class="error">&nbsp:</label>
           </td>
       </tr>
        <tr>
            <td>mailbox</td>
            <td>
                <input type="text" name="email" id="email"/>
            </td>
            <td>
                <label id="emailError" class="error"></label>
            </td>
        </tr>
        <tr>
            <td>describe</td>
            <td>
                <textarea rows="5" cols="30" name="description"></textarea>
            </td>
            <td>
                <label id="discriptionError" class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" name="submit"/>
                <input type="reset" name="reset"/>
            </td>
        </tr>
    </table>
</form>

</body>
</html>

Inside the page is a form, and then I set up a hidden item when submitting a form: method:add, that is to say, when submitting to / Customer Servlet, the field will be brought up, and the background can determine what action to perform by retrieving the field. This is to facilitate the unified management of background code, so as not to look at the code when you can not find the entry.

We see the submission to / Customer Servlet, so let's create a new Servlet:
src right-click - > New - > servlet, name fills Customer Servlet, package fills servlet. Here I wrote a BaseServlet. Let this servlet integrate BaseServlet, BaseServlet help us do a good method reflection.
Here we post the BaseServlet related.

BaseServlet.java

import servlet.GetRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {
    public BaseServlet() {
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(((HttpServletRequest)request).getMethod().equalsIgnoreCase("get")) {
            if(!(request instanceof GetRequest)) {
                request = new GetRequest((HttpServletRequest)request);
            }
        } else {
            ((HttpServletRequest)request).setCharacterEncoding("utf-8");
        }

        response.setContentType("text/html;charset=UTF-8");
        String methodName = ((HttpServletRequest)request).getParameter("method");
        Method method = null;

        try {
            method = this.getClass().getMethod(methodName, new Class[]{HttpServletRequest.class, HttpServletResponse.class});
        } catch (Exception var10) {
            throw new RuntimeException("The method you want to call:" + methodName + "It does not exist!", var10);
        }

        try {
            String e = (String)method.invoke(this, new Object[]{request, response});
            if(e != null && !e.trim().isEmpty()) {
                int index = e.indexOf(":");
                if(index == -1) {
                    ((HttpServletRequest)request).getRequestDispatcher(e).forward((ServletRequest)request, response);
                } else {
                    String start = e.substring(0, index);
                    String path = e.substring(index + 1);
                    if(start.equals("f")) {
                        ((HttpServletRequest)request).getRequestDispatcher(path).forward((ServletRequest)request, response);
                    } else if(start.equals("r")) {
                        response.sendRedirect(((HttpServletRequest)request).getContextPath() + path);
                    }
                }
            }

        } catch (Exception var9) {
            throw new RuntimeException(var9);
        }
    }
}

GetRequest .java

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class GetRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public GetRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    public String getParameter(String name) {
        String value = this.request.getParameter(name);
        if(value == null) {
            return null;
        } else {
            try {
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException var4) {
                throw new RuntimeException(var4);
            }
        }
    }

    public Map getParameterMap() {
        Map map = this.request.getParameterMap();
        if(map == null) {
            return map;
        } else {
            Iterator var3 = map.keySet().iterator();

            while(var3.hasNext()) {
                String key = (String)var3.next();
                String[] values = (String[])map.get(key);

                for(int i = 0; i < values.length; ++i) {
                    try {
                        values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
                    } catch (UnsupportedEncodingException var7) {
                        throw new RuntimeException(var7);
                    }
                }
            }

            return map;
        }
    }
}

Next we implement the add method:

public class ConstomerServlet extends BaseServlet {
private CustomerServier customerService= new CustomerServier();

    public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Customer customer = CommonUtils.toBean(request.getParameterMap(), Customer.class);
        customer.setId(CommonUtils.uuid());

        customerService.add(customer);
        request.setAttribute("msg", "Congratulations on successfully adding customers");
        return "/msg.jsp";
    }
 }

Here we need to create a new public display page msg.jsp. The job of this page is to extract and display msg.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1 style="color:green;" align="center">${msg}</h1>

</body>
</html>

Then the implementation of the method requires us to build a Model to save the data submitted by the user. Here we use a library, which is commons.beanutils. At the same time, we create two new files: CommonUtils.java and DateConverter.java.
Actually, like the common components above, we can pack them into a jar package and save them.

CommonUtils.java

import commons.DateConverter;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

public class CommonUtils {
    public CommonUtils() {
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

    public static <T> T toBean(Map map, Class<T> clazz) {
        try {
            Object e = clazz.newInstance();
            ConvertUtils.register(new DateConverter(), Date.class);
            BeanUtils.populate(e, map);
            return e;
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }
}

DateConverter.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;

public class DateConverter implements Converter {
    public DateConverter() {
    }

    public Object convert(Class type, Object value) {
        if(value == null) {
            return null;
        } else if(!(value instanceof String)) {
            return value;
        } else {
            String val = (String)value;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            try {
                return sdf.parse(val);
            } catch (ParseException var6) {
                throw new RuntimeException(var6);
            }
        }
    }
}

Customer.java

public class Customer
{
    private String id;
    private String name;
    private String gender;
    private String phone;
    private String email;
    private String description;

    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 String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

To make the logic clearer, we created a new Service class to handle the business logic.
CustomerServier .java

public class CustomerServier {
    CustomerDao customerDao = new CustomerDao();

    public void add(Customer customer)
    {
        customerDao.add(customer);
    }
 }

The database has a special class to handle, Customer Dao
CustomerDao.java

public class CustomerDao {

    private QueryRunner qr = new TxQueryRunner();


    public void add(Customer c) {
        try {
            String sql = "insert into t_customer values(?,?,?,?,?,?)";
            Object[] params = {c.getId(), c.getName(), c.getGender(),
                    c.getPhone(), c.getEmail(), c.getDescription()};

            qr.update(sql, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
  }

We need to create two new tool classes here: JdbcUtils, TxQuery Runner
TxQueryRunner.java

import jdbc.JdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class TxQueryRunner extends QueryRunner {
    public TxQueryRunner() {
    }

    public int[] batch(String sql, Object[][] params) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int[] result = super.batch(con, sql, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }

    public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        Object result = super.query(con, sql, rsh, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }

    public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        Object result = super.query(con, sql, rsh);
        JdbcUtils.releaseConnection(con);
        return result;
    }

    public int update(String sql) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql);
        JdbcUtils.releaseConnection(con);
        return result;
    }

    public int update(String sql, Object param) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql, param);
        JdbcUtils.releaseConnection(con);
        return result;
    }

    public int update(String sql, Object... params) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }
}

From this point, we can see how important it is to have a tool class component library for Web development. JdbcUtils uses the database connection pool c3p0, so we need to create a new xml file in the src directory to configure one
JdbcUtils.java

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

public class JdbcUtils {
    private static DataSource ds = new ComboPooledDataSource();
    private static ThreadLocal<Connection> tl = new ThreadLocal();

    public JdbcUtils() {
    }

    public static DataSource getDataSource() {
        return ds;
    }

    public static Connection getConnection() throws SQLException {
        Connection con = (Connection)tl.get();
        return con != null?con:ds.getConnection();
    }

    public static void beginTransaction() throws SQLException {
        Connection con = (Connection)tl.get();
        if(con != null) {
            throw new SQLException("Business has been started, can not be repeated open!");
        } else {
            con = ds.getConnection();
            con.setAutoCommit(false);
            tl.set(con);
        }
    }

    public static void commitTransaction() throws SQLException {
        Connection con = (Connection)tl.get();
        if(con == null) {
            throw new SQLException("No transaction can not be committed!");
        } else {
            con.commit();
            con.close();
            con = null;
            tl.remove();
        }
    }

    public static void rollbackTransaction() throws SQLException {
        Connection con = (Connection)tl.get();
        if(con == null) {
            throw new SQLException("No transaction can be rolled back!");
        } else {
            con.rollback();
            con.close();
            con = null;
            tl.remove();
        }
    }

    public static void releaseConnection(Connection connection) throws SQLException {
        Connection con = (Connection)tl.get();
        if(connection != con && connection != null && !connection.isClosed()) {
            connection.close();
        }

    }
}

c3p0-config.xml
This is my database configuration, the specific configuration changes according to each person's computer. As for the meaning of the specific fields in it, I will not introduce them one by one.

<?xml version="1.0" encoding="utf-8" ?>
<c3p0-config>
    <default-config>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/customer</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>

At this point, the operation of our new customers is done, to run and see the effect. Running is the playback key.
Well, the effect is coming out, and we have succeeded in building a new one. Looking at the database, I did insert it. Some students will say that the database code has not been posted out yet? Okay, I'll post the tables of database design.
t_customer.sql

/*
Navicat MySQL Data Transfer

Source Server         : larsonconn
Source Server Version : 50520
Source Host           : localhost:3306
Source Database       : customer

Target Server Type    : MYSQL
Target Server Version : 50520
File Encoding         : 65001

Date: 2017-05-18 14:54:29
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_customer`
-- ----------------------------
DROP TABLE IF EXISTS `t_customer`;
CREATE TABLE `t_customer` (
  `id` varchar(50) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `gender` varchar(20) DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `description` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Implementing queries

Let's see top.jsp is written like this.
That door needs to implement the findAll method in the servlet:

 public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       /*
        *1.Get the pc passed by the page
        * 2.Given the value of pr
        * 3.Call service method with pc and pr to get pageBean and save it to request domain
        * 4.Forward to list.jsp
        */
       /*
        * 1.Get pc
        *   If the pc parameter does not exist, pc = 1
        *   If the pc parameter exists, it needs to be converted to int type
        */
        int pc=getPc(request);

        int pr=10;//Given the value of pr, 10 rows per page are recorded

        PageBean<Customer> pb= customerService.findAll(pc,pr);
        pb.setUrl(getUrl(request));

        request.setAttribute("pb",pb);

        return "f:/list.jsp";
    }

Because paging queries are used, we need to build another Bean.
PageBean.java

public class PageBean<Object>
{
    private int pc;//Current page code
    //private int tp; / / total pages
    private int tr;//Total record tatal records
    private int pr;//Number of records per page page page
    private List<Object> beanList;//Current page record
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getPc() {
        return pc;
    }

    public void setPc(int pc) {
        this.pc = pc;
    }

    public int getTp()
    {
        int tp=tr/pr;
        return tr % pr == 0 ? tp : tp + 1 ;
    }



    public int getTr() {
        return tr;
    }

    public void setTr(int tr) {
        this.tr = tr;
    }

    public int getPr() {
        return pr;
    }

    public void setPr(int pr) {
        this.pr = pr;
    }

    public List<Object> getBeanList() {
        return beanList;
    }

    public void setBeanList(List<Object> beanList) {
        this.beanList = beanList;
    }
}

Then service implements findAll method:

public PageBean<Customer> findAll(int pc, int pr) {
        return customerDao.findAll(pc,pr);
    }

Then comes the Dao layer implementation: query how many records there are first, and paginate when there are more records. Use the limit instruction to implement.

public PageBean<Customer> findAll(int pc, int pr) {
        try {
            /*
             *1.He needs to create the pageBean object pb
             * 2.Setting pc and pr of pb
             * 3.Get tr and set it to pb
             * 4.Get the bean List set to pb
             * Finally return to pb
             */
            PageBean<Customer> pb = new PageBean<>();
            pb.setPc(pc);
            pb.setPr(pr);

            String sql = "select count(*) from t_customer";
            Number number = (Number) qr.query(sql, new ScalarHandler<>());

            int tr = number.intValue();
            pb.setTr(tr);

            sql = "select * from t_customer order by name limit ?,?";
            Object[] params = {(pc - 1) * pr, pr};
            List<Customer> beanList = qr.query(sql, new BeanListHandler<>(Customer.class), params);

            pb.setBeanList(beanList);

            return pb;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

Now that we have the data, we need to display it. We have created a new jsp to display the data:
list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Customer List</title>
</head>
<body>
    <h3 align="center" >Customer List</h3>
    <table border="1" width="70%" align="center">
        <tr>
            <th>Customer Name</th>
            <th>Gender</th>
            <th>Mobile phone</th>
            <th>mailbox</th>
            <th>describe</th>
            <th>operation</th>
        </tr>
        <c:forEach items="${pb.beanList}" var="cstm">
        <tr>
            <td>${cstm.name}</td>
            <td>${cstm.gender}</td>
            <td>${cstm.phone}</td>
            <td>${cstm.email}</td>
            <td>${cstm.description}</td>
            <td>
                <a href="<c:url value='/CustomerServlet?method=preEdit&id=${cstm.id}'/> ">edit</a>
                <a href="<c:url value='/CustomerServlet?method=delete&id=${cstm.id}'/> ">delete</a>
            </td>
        </tr>
        </c:forEach>
    </table>
<br/>
<center>
    The first ${pb.pc}page/common ${pb.tp}page
    <a href="${pb.url}&pc=1">home page</a>
    <c:if test="${pb.pc>1}">
        <a href="${pb.url}&pc=${pb.pc-1}">Previous page</a>
    </c:if>

    <c:choose>
        <c:when test="${pb.tp<=10}">
            <c:set var="begin" value="1"/>
            <c:set var="end" value="${pb.tp}"/>
        </c:when>
        <c:otherwise>
            <c:set var="begin" value="${pb.pc-5}"/>
            <c:set var="end" value="${pb.pc+4}"/>
            <%--Head overflow--%>
            <c:if test="${begin<1}">
                <c:set var="begin" value="1"/>
                <c:set var="end" value="10"/>
            </c:if>
            <%--Tail overflow--%>
            <c:if test="${end>pb.tp}">
                <c:set var="end" value="${pb.tp}"/>
                <c:set var="begin" value="${pb.tp-9}"/>
            </c:if>
        </c:otherwise>
    </c:choose>

    <%--Loop through the list of page numbers--%>
    <c:forEach var="i" begin="${begin}" end="${end}">
        <c:choose>
            <c:when test="${i eq pb.pc}">
                [${i}]
            </c:when>
            <c:otherwise>
                <a href="${pb.url}&pc=${i}">[${i}]</a>
            </c:otherwise>
        </c:choose>

    </c:forEach>


    <c:if test="${pb.pc<pb.tp}">
    <a href="${pb.url}&pc=${pb.pc+1}">next page</a>
    </c:if>
    <a href="${pb.url}&pc=${pb.tp}">Tail page</a>

</center>

</body>
</html>

All right, list.jsp reads and displays the data from the incoming object, and the query function is implemented here.

When that query is finished, let's do some advanced queries. Advanced queries can specify information queries. When you enter from the top page, you see that there is / query.jsp. Let's build a / query.jsp.
/query.jsp'

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title></title>
</head>
<body>
    <h3 align="center">Advanced Search</h3>
    <form action="<c:url value="/CustomerServlet"/>" method="get">
        <input type="hidden" name="method" value="query">
        <table border="0" align="center" width="40%" style="margin-left: 100px">
            <tr>
                <td width="100px">Customer Name</td>
                <td width="40%">
                    <input type="text" name="name">
                </td>
            </tr>
            <tr>
                <td>Client Gender</td>
                <td>
                    <select name="gender">
                        <option value="">==Please choose gender.==</option>
                        <option value="male">male</option>
                        <option value="female">female</option>
                    </select>
                </td>
            </tr>
            <tr>
            <td>Mobile phone</td>
            <td>
                <input type="text" name="phone"/>
            </td>
            </tr>
            <tr>
                <td>mailbox</td>
                <td>
                    <input type="text" name="email"/>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>

                    <input type="submit" value="search"/>
                    <input type="reset" value="Reset"/>
                </td>
            </tr>

        </table>
    </form>

</body>
</html>

Now that the query form is written, let's implement the query method or go back to Servlet.

  public String query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Customer customer=CommonUtils.toBean(request.getParameterMap(),Customer.class);

//        System.out.println(getUrl(request));
        customer=encoding(customer);

        int pc=getPc(request);
        int pr=10;

        PageBean<Customer> pb=  customerService.query(customer,pc,pr);

        pb.setUrl(getUrl(request));

        request.setAttribute("pb",pb);
        return "/list.jsp";

    }

Let's implement the query method in service:

  public PageBean<Customer> query(Customer customer, int pc, int pr) {
        return customerDao.query(customer, pc,pr);
    }

Then there's the query in Dao: the root Query All is about the same, just where query restrictions are made

public PageBean<Customer> query(Customer customer, int pc, int pr) {
        try {
            PageBean<Customer> pb = new PageBean<Customer>();
            pb.setPc(pc);
            pb.setPr(pr);

            StringBuilder cntSql = new StringBuilder("select count(*) from t_customer ");
            StringBuilder whereSql = new StringBuilder(" where 1=1 ");
            List<Object> params = new ArrayList<Object>();

            String name = customer.getName();

            if (name != null && !name.trim().isEmpty()) {
                whereSql.append("and name like ?");
                params.add("%" + name + "%");
            }

            String gender = customer.getGender();
            if (gender != null && !gender.trim().isEmpty()) {
                whereSql.append("and gender=?");
                params.add(gender);
            }

            String phone = customer.getPhone();
            if (phone != null && !phone.trim().isEmpty()) {
                whereSql.append("and phone like ?");
                params.add("%" + phone + "%");
            }

            String email = customer.getEmail();
            if (email != null && !email.trim().isEmpty()) {
                whereSql.append("and email like ?");
                params.add("%" + email + "%");
            }
            Number num = (Number) qr.query(cntSql.append(whereSql).toString(), new ScalarHandler<>(), params.toArray());

            pb.setTr(num.intValue());

            StringBuilder sql = new StringBuilder("select * from t_customer ");
            StringBuilder lmitSql = new StringBuilder(" limit ?,?");

            params.add((pc - 1) * pr);
            params.add(pr);

            List<Customer> beanList = qr.query(sql.append(whereSql).append(lmitSql).toString(), new BeanListHandler<>(Customer.class), params.toArray());
            pb.setBeanList(beanList);

            return pb;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

We put the query results on the list.jsp display page, which is written in front of us, so let's run it.
Very good. It's shown correctly.
Next is the modification and deletion.
Modify the Delete Entry and I put it on the list page.
c:url value='/CustomerServlet?method=preEdit&id=${cstm.id}'

Modify customer information

  public String preEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Customer customer = customerService.find(id);

        request.setAttribute("customer", customer);

        return "/edit.jsp";
    }

We first query the customer id we need to modify, query the customer information through the database, and then transfer it to the edit page for editing.
CustomerServier.java

...
 public Customer find(String id) {
        return customerDao.find(id);
    }
 ...

CustomerDao.java

...
   public Customer find(String id) {
        try {
            String sql = "select * from t_customer where id=?";
            return qr.query(sql, new BeanHandler<Customer>(Customer.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
...

Let's create a new edit.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3 align="center">Editorial Clients</h3>
<form action="<c:url value='/CustomerServlet'/>" method="post" >
    <input type="hidden" name="method" value="edit"/>
    <input type="hidden" name="id" value="${customer.id}"/>
    <table border="0" align="center" width="40%" style="margin-left: 100px">
        <tr>
            <td width="100px">Customer Name</td>
            <td width="40%">
                <input type="text" name="name" value="${customer.name}"/>
            </td>
            <td align="left">
                <label id="nameError" class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td>Client Gender</td>
            <td>
                <input type="radio" name="gender" value="male" id="male" <c:if test="${customer.gender eq 'male'}"/>checked="checked"/>
                <label for="male">male</label>
                <input type="radio" name="gender" value="female" id="female" <c:if test="${customer.gender eq 'female'}"/> checked="checked"/>
                <label for="female">female</label>
            </td>
            <td>
                <label id="genderError"class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td>Mobile phone</td>
            <td>
                <input type="text" name="phone" id="phone" value="${customer.phone}"/>
            </td>
            <td>
                <label id="phoneError"class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td>mailbox</td>
            <td>
                <input type="text" name="email" id="email" value="${customer.email}"/>
            </td>
            <td>
                <label id="emailError"class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td>describe</td>
            <td>
                <textarea rows="5" cols="30" name="description">${customer.description}</textarea>
            </td>
            <td>
                <label id="discriptionError"class="error">&nbsp;</label>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" name="submit" value="Editorial Clients"/>
                <input type="reset" name="reset"/>
            </td>
        </tr>
    </table>
</form>


</body>
</html>

Okay, when we click submit, we will put the modified user information into the form and teach the servlet's edit method. Now we implement the edit method:

...
  public String edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Customer customer = CommonUtils.toBean(request.getParameterMap(), Customer.class);

        customerService.edit(customer);

        request.setAttribute("msg", "Congratulations, Editor's Client Success");
        return "/msg.jsp";
    }
...

Okay, here we are. We have finished the modification operation. Haha ha ha ha ha ha ha ha ha ha. That leaves a deletion operation.

Delete customers

Delete client calls the delete method of servlet:
c:url value='/CustomerServlet?method=delete&id=${cstm.id}'
Now let's implement the delete method:

...
public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");

        customerService.delete(id);

        request.setAttribute("msg", "Congratulations on the success of deleting customers");

        return "/msg.jsp";
    }
...

Or as before:
CustomerServier.java

...
 public void delete(String id) {
        customerDao.delete(id);
    }
...

CustomerDao.java

...
 public void delete(String id) {
        try {
            String sql = "delete from t_customer where id=?";
            qr.update(sql, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
...

Okay, we're done with deletion. This is a great success. A simple customer management system is completed. You need lib to click here:

Click here:

Topics: Java JSP SQL Database