java web project--learning through building 4

Tue, Jan 12, 2021 5-minute read

a full-stack web application for users to understand java web system

three-tier system of the project

sp1. create sql forms

  • database book
  • t_user

sp2. JaveBean User (id, username, password, email)

sp3. JdbcUtils

  • jar package
  • jdbc.properties in src dir
username=root
password=root
url=jdbc:mysql://localhost:3306/book
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=1
  • Jdbc tool

sp4. BaseDao

  • commons-dbutils jar
  • BaseDao
public abstract class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();

    /**
    * update() : insert/update/delete
    *
    */ 
    public int update(String sql, Object... args) {
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.update(connection, sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
            return -1;
        }
    }

     /**
    * query() : 
    * return javaBean
    */ 
    public <T> T queryForOne(Class<T> type, String sql, Object... args) {
        Connection con = JdbcUtils.getConnection();
        try {
            return queryRunner.query(con, sql, new BeanHandler<T>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
            return null;
        }
    }

    
     /**
    * query() : 
    * return multiplate javaBean
    */ 
    public <T> T queryForList(Class<T> type, String sql, Object... args) {
        Connection con = JdbcUtils.getConnection();
        try {
            return queryRunner.query(con, sql, new BeanListHandler<T>(type), args);
    }

    /**
    * query() : 
    * return sql
    */ 
    public Object queryForSingleValue(String sql, Object... args) {
        Connection conn = JdbcUtils.getConnection();
        try {
            return queryRunner.query(conn, sql, new ScalarHandler(), args);
    }

sp5. UserDao && test

  • UserDao interface
public intercface UserDao {
    /**
    * @param username
    * 
    */ 
    public User queryUserByUsername(String username);

    public User queryUserByUsernameAndPassword(String username, String password);

    public int saveUser(User user);
}
  • UserDaoImpl
public class UserDaoImpl extend BaseDap implements UserDao {
    /**
    * @param username
    * 
    */ 
    public User queryUserByUsername(String username) {
        String sql = "select `id`,`username`,`password`,`email` from t_user where username = ?";
        return queryForOne(User.class, sql, username);
    }

    public User queryUserByUsernameAndPassword(String username, String password){

    }

    public int saveUser(User user){

    }
}
  • UserDao test
UserDao userDao = new UserDaoImpl();
@Test
public void queryUserByUsername() {
if (userDao.queryUserByUsername("admin1234") == null ){
System.out.println("aaaaaa!");
} else {
System.out.println("bbbbbbbbb");
}

sp6. UserService && test

  • UserService interface
public intercface UserService {
    /**
    * @param username
    * 
    */ 
    public void registUser(User user);

    public User login(User

    public boolean existsUsername(String username);
}
  • UserServiceImpl

  • UserService test

sp7. web

  • regist

    • when user finish regist, click sumbit button, send the parameter to service and save user data

    • modify regist.html and regist_success.html page

    • RegistServlet

    public class RegistServlet extends HttpServlet {
        private UserService userService = new UserServiceImpl();

        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {

            // 1. get parameter
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String email = req.getParameter("email");
            String code = req.getParameter("code");

            // 2. check the code
            if ("abcde".equalsIgnoreCase(code)) {
            // 3、check the username
            if (userService.existsUsername(username)) {
                System.out.println("username[" + username + "]exist!");
                // back to regist page
                req.getRequestDispatcher("/pages/user/regist.html").forward(req, resp);
            } else {
            // available
            // invoke Sservice save to SQL database
                userService.registUser(new User(null, username, password, email));
                // go to the regist_success.html
                req.getRequestDispatcher("/pages/user/regist_success.html").forward(req, resp);
                }
            } else {
                System.out.println("code[" + code + "]error");
                req.getRequestDispatcher("/pages/user/regist.html").forward(req, resp);
            }
}
}

file upload and download

file upload

  • form, method = post
  • form encType: multipart/form-data
  • form input type=file
  • servlet reveice and deal with data upload

commos-fileupload.jar

  • commons-fileupload-x.x.x.jar
  • commons-io-x.x.jar

These two jars contains classes we can use:

  • ServletFileUpload: decode upload data
  • boolean ServletFileUpload.isMultipartContent(HttpServletRequest request);
  • public List parseRequest(HttpServletRequest request);
  • boolean FileItem.isFormField(), check is ordinary form or not
  • String FileItem.getFieldName()
  • String FileItem.getString()
  • String FileItem.getName()
  • void FileItem.write(file)

fileupload

<form action="http://192.168.1.68://8080/book/uploadServlet" method="post" enctype="multipart/form-data">
username: <input type="text" name="username" /><br>
username: <input type="file" name="photo" /><br>
<input type="submit" value="upload" /><br>
</form>

decode data upload

/**
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
    // 1. check the data is multipart
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactroy fileItemFactroy = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactroy);
        try {
            // decode data, get FileItem
            List<FileItem> list = servletFileUpload.parseRequest(req);

            for (FileItem fileItem : list) {
                if (fileItem.isFormField()) {
                  System.out.println(" name value:" + fileItem.getFieldName());
                    // 参数 UTF-8.解决乱码问题
                    System.out.println("form value value:" + fileItem.getString("UTF-8"));
                } else {
                // 上传的文件
                System.out.println("name value:" + fileItem.getFieldName());
                System.out.println("upload file name:" + fileItem.getName());
                fileItem.write(new File("e:\\" + fileItem.getName()));
            }
        }
}
         

file download

  • response.getOutputStream();
  • servletContext.getResourceAsStream();
  • servletContext.getMimeType();
  • response.getContentType();
  • response.setHeader(“Content-Disposition”, “attachment;fileName=1.jpg”);
String us = request.getHeader("User-Agent");
// whether is Fire fox web 
if (us.contains("Firefox")) {
    String str = "attachment;fileName" + "=?utf-8?B?" + new BASE64Encoder().encode("中文.jpg".getBytes("utf-8"))
    + "?="; 
    response.setHeader("Content-Disposition", str);
} else {
     String str = "attachment;fileName" + URLEncode.encode("中文.jpg".getBytes("utf-8"))
    + "?="; 
    response.setHeader("Content-Disposition", str);
}

chorme: the first time tomcat

  • usename: 〰️ ▶️ login.jsp

  • password ◀️ 〰️ back to login page

  • submit 〰️ ▶️ LoginServlet 1. get username and password 2. validate

. ❌ not allow to login display username Set-Cookie:username ◀️ 〰️ ✔️: save username as Cookie send to server

<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
用户名<input type="text" name="username" value="${cookie.username.value}"> <br>
密码<input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>

LoginServlet

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("wzg168".equals(username) && "123456".equals(password)) {
//login success
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60 * 60 * 24 * 7);// cookie is available in a week
resp.addCookie(cookie);
System.out.println("login success");
} else {
// login fails
System.out.println("login fails");
}
}

Session to invalidate the user infomation

UserServlet

protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// 1、invalidate Session username
req.getSession().invalidate();
// 2、redirect to login page
resp.sendRedirect(req.getContextPath());
}

Order module

Order page

Order page

  • orderId
  • createTime
  • price
  • status
  • userId

Order Item

  • id
  • name
  • count
  • price
  • totalPrice
  • orderId

Order function

  • create order
  • show all orders
  • send order
  • show my order
  • totalPrice
  • receive order

Order Servlet

OrderService

OrderDao

  • saveOrder(order)
  • queryOrders()
  • changeOrderStatus(OrderId, status);
  • queryOrderByUserId(userId);

OrderItemDao

  • saveOrderItem(orderItem)
  • queryOrdersItemByOrderId(orderId)

javaweb1

javaweb2

javaweb3

javaweb5

spring

springmvc