User Management Based on Servlet and JSP

Recently, I learned the javaweb link and implemented a user management system following the teacher's teaching steps. No more bb, just start.

First step: database design

For the time being, the system only uses one user table, which is equivalent to any login user can add, delete and modify the table. The database is designed as follows:

create database day17; //Create a database
use day17;
create table user(
    id int primary key auto_increment,
    name varchar(20) not null,
    gender varchar(5),
    age int,
    address varchar(32),
    qq varchar(20),
    email varchar(50),
    username varchar(20),
    password varchar(20)
);

Then create a javaweb project in IDEA. Next, create a WEB-INF under the web folder, then create a lib folder under it, and import the required packages into it.

Next, a series of pre-prepared front-end page templates are introduced under the web folder.

Folder as shown in the figure, the environment has been built.

Step 2: Implement the first function list query. Click on the query, you can query the database, so user information

Explain why this is UserService = new UserService Impl (); if there is a problem with the implementation class, change it directly in the implementation class without changing the method of the interface class.

The third step is to create the User object under the domain package and add setter, getter and toString methods.

public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String address;
    private String qq;
    private String email;
    private String username;
    private String password;
}

Step 4: In the index. jsp page click jump to set click jump path

  <a
            href="${pageContext.request.contextPath}/userListServlet" style="text-decoration:none;font-size:33px">Query all user information
    </a>

This place is ${pageContext.request.contextPath}, which dynamically gets the virtual path. There is no userListServlet path at this time, but it doesn't matter. You can create it at this time. But when you want to query data with service, you find that this method is not available. It's also the interface to create service under the service package just after the servlet has been created.

Step 5: Create the UserService interface under the service package

public interface UserService {
    /**
     * Query all user information
     */
    public List<User> findAll();
}

Create its implementation class again

public class UserServiceImpl implements UserService {
    @Override
    public List<User> findAll() {
        //Call dao to complete the query
        return null;
    }
}

There is no call dao inside to complete the query for the time being, but don't worry, just go ahead and implement it by yourself.

Step 6:

UserDao: 
public interface UserDao {
    public List<User> findAll();
}
UserdaoImpl:
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        //Using JDBC to operate database
        return null;
    }
}

This time go to UserService Impl

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();
    @Override
    public List<User> findAll() {
        //Call dao to complete the query
        return dao.findAll();
    }
}

With the findAll method of UserService, you can go to the Servlet to implement it concretely at this time.

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Call UserService to complete the query
        UserService service = new UserServiceImpl();
        List<User> users = service.findAll();
        //2. Store the list in the request domain
        request.setAttribute("users",users);
        //3. Forward to list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

Step 7: Next you need to write jdbc

First import the configuration file

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day17
username=root
password=521029
# Number of Initialized Connections
initialSize=5
# maximum connection
maxActive=10
# Maximum waiting time
maxWait=3000

Writing Tool Class

package edu.swpu.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC Tool classes use the Durid connection pool
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1. Loading configuration files
            Properties pro = new Properties();
            //Use ClassLoader to load the configuration file to get the byte input stream
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2. Initialize connection pool objects
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get the connection pool object
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * Get the Connection object
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

Finally, improve the JDBC method

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template =new JdbcTemplate(JDBCUtils.getDataSource());
    
    @Override
    public List<User> findAll() {
        //Using JDBC to operate database
        //1. Define sql
        String sql = "select * from user";
        List<User> users =template.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return users;
    }
}

For the user information queried, it should be displayed in a loop. At this time, we need to use the jstl statement and add the first sentence of jsp.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

At this point in the page loops display the information found, front-end code

<c:forEach items="${users}" var="user" varStatus="s">
            <tr>
                <td>${s.count}</td>
                <td>${user.name}</td>
                <td>${user.gender}</td>
                <td>${user.age}</td>
                <td>${user.address}</td>
                <td>${user.qq}</td>
                <td>${user.email}</td>
                <td><a class="btn btn-default btn-sm" href="update.html">modify</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
            </tr>
        </c:forEach>

If you encounter a problem, the jsp page you encounter must declare one sentence at the beginning

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

Otherwise, the code will be scrambled.

Keywords: Database JDBC Java JSP

Added by David03 on Wed, 14 Aug 2019 06:22:21 +0300