Beginners use JavaWeb to write one of the most common registration and login pages

Posted by Cragsterboy on Sun, 20 Feb 2022 06:46:21 +0100

It is just a most common registration and login page written by Java Web for beginners. You only need to enter your user name and password

Only part of the java code is listed and explained. The database, configuration process, configuration file and html front-end interface follow their own capabilities

I First use the JDBC utils tool class to connect to the database

 1. JDBCUtil s. class. getClassLoader(). Getresourceasstream ("druid. Properties"): get the class loader of the JDBC util class and return an input stream that reads the specified file location

2.pro.load(is): Generally speaking, I understand how to convert the incoming byte input stream into a character stream and wrap it with BufferedReader. How to read the corresponding configuration file, read one line at a time, divide it into two strings, and store them respectively. Properties is a subclass of map

2.DruidDataSourceFactory.createDataSource(): Alibaba's database connection pool Druid is used to initialize the connection pool object

private static DataSource ds;
//Static code block
static {
    try {
        //Load profile
        Properties pro = new Properties();
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //Initialize connection pool object
        ds = DruidDataSourceFactory.createDataSource(pro);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//Get connection pool object
public static DataSource getDs(){
    return ds;
}
/*
Get Connection object
 */
public static Connection getConnection() throws SQLException {
    return ds.getConnection();
}

II Table data is normal. Just use getter and setter to encapsulate private member variables and rewrite toString method

III registdao() method: when registering, query whether the user name already exists

JdbcTemplate is used to encapsulate Spring's JDBC, which makes it easier to add, delete, modify and query the database

Precautions for using queryForObject: the parameters passed are:

1. Written sql statement

2. Pass a BeanPropertyRowMapper object: used to map the properties of Java objects and the field names of MySQL tables

3..... Set for injection? Value of placeholder

public class registdao{
        private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDs());
        public User getname(User registUser){
            try {
                String sql="select * from user where username = ?;";
                User user = template.queryForObject(sql,
                        new BeanPropertyRowMapper<User>(User.class),
                        registUser.getUsername());
                return user;
            } catch (DataAccessException e) {
                e.printStackTrace();
                return null;
            }
        }
}

IV The userregister () method inherits the registdao() method: if the registration is successful, it will be inserted into the database

Similarly, use JdbcTemplate to encapsulate and update to modify the database
public class Userregist extends registdao{
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDs());
    public int regist(User registUser) {
        String sql = "insert into user values (null,?,?);";
        int i = template.update(sql, registUser.getUsername(), registUser.getPassword());
        return i;
    }
}

V Register the code in the doPost method of the Servlet

1.request.getParameterMap() method: for the data of all input tags in the form, its name is the key and its value is the value

2. Remember here that it is a mapped process. BeanUtils,populate (Object bean, Map properties) method: map the data in the map to the get and set methods in JavaBean

3. The forwarding process of register takes the successful registration as an example:

     request.setAttribute (String s,Object o) can only be passed once. The parameters are the attribute and value to be forwarded

     request.getRequestDispatcher(String URL).forward(request,response): the address where the request is forwarded

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        User registUser = new User();
        try {
            BeanUtils.populate(registUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Userregist userregist = new Userregist();
        User user = userregist.getname(registUser);
        if(user==null){
            userregist.regist(registUser);
            request.setAttribute("user",registUser);
            request.getRequestDispatcher("/successRegist").forward(request,response);
        }else {
            request.getRequestDispatcher("/failRegist").forward(request,response);
        }
    }
 

6: SuccessRegist registration success page doPost method:

 1.request.getParameter(): accept the parameter forwarded and convert it into User type, then use the get() method

 2.response.getWriter().write(Sting s): the text format of the printout

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getAttribute("user");
        if(user!=null){
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("congratulations!"+user.getUsername()+"Registration succeeded!");
        }
    }
Registration failed. The interface is similar

The login interface is simpler, just query in the database

The interface is very simple and is still learning

Topics: Java JavaEE Maven intellij-idea