Get the data in the input box of the JSP page

Use Java Bean to get the data in the input box to
make a dynamic web page. The most important thing is the interaction of background data. In static pages, the data is already completed when the web page is created, while in dynamic pages, the data exists dynamically For example, the user name after login is displayed, which is dynamically displayed by acquiring the data in the background database during the running process of the web page.
In the acquisition of data, you can use the request.getParameter() method to obtain the data in the web page in turn. In this process, there is a regulation, the parameter name in the web page, the attribute name in the entity class, and the keyword in the database The names must match.
However, in this method, if it is used in the registration page, there will be a huge amount of code. Another way is to create a management class object of the entity class through reflection, create a new map collection, and convert the map collection into a set Collection, use the enhanced for loop to obtain key-value pairs, obtain a field object through the getDeclaredField(paramName) method of the management class, and open the permission to assign private attributes of attributes. Then get the value, but in this method, the types of key-value pairs are not uniform, and an error will occur.
Therefore, the C3p0Util tool class and the BeanUtil tool class can be introduced. First, create a C3p0Util tool class and write the following code in the class:

 public static <T>T mapToBean(Class<T> c, Map map){
        try {
            T t = c.newInstance();
            BeanUtils.populate(t,map);
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

Then create a Servlet class and write the following code in doPost:

  request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = C3p0Util.mapToBean(User.class, map);
        System.out.println(user);

Now you can run the web page and enter the content to test whether the code is successful.
Of course, by adding a database addition, deletion, modification, and query statement in the code behind, the synchronization between the database and the web page can be achieved!

Guess you like

Origin blog.csdn.net/fzt12138/article/details/90579552