Case (web development): website login (using servlet)

Case needs:

On the site's home page, login link, click on the login link, you can jump to the page to log in. Enter the username and password case click login page to log in. Login completion.
Here Insert Picture Description

demand analysis:

Here Insert Picture Description

Implementation steps

  • Create a database table

  • Login.html create a login page in the WEB-INF (path of action submitted to action = "/ name of the module / Servlet Path", and then create form form)

  • Creating WEB Project

    • Add the necessary jar (to create a lib in the WEB-INF web folder in the folder to store the three jar package), configuration files (stored C3P0 connection pool in the src folder, create a folder under the src of a utils package for the storage of tools of C3P0)
    • Create a User entity class (corresponding with the database)
    • Create your own package (storage servlet)
  • Written page

  • Writing Server Servlet

  方法: String getParameter("表单的name属性值") 返回值String,表单填写内容

Create a database table

-- 创建数据库web02
CREATE DATABASE web02;
-- 使用数据库web02
USE web02;
-- 创建表user 字段:主键,用户名,密码
CREATE TABLE USER (
	-- 主键
	uid INT PRIMARY KEY AUTO_INCREMENT,
	-- 用户名
	username VARCHAR(50),
	-- 密码
	PASSWORD VARCHAR(50)
);

-- user表插入初始化数据
INSERT INTO USER VALUES(NULL,'tom','123'),(NULL,'jerry','456');

-- 登录使用用户名和密码作为条件查询
SELECT * FROM USER WHERE username='tom' AND PASSWORD = '123'; -- 登录成功
SELECT * FROM USER WHERE username='tom' AND PASSWORD = '456'; -- 登录失败
/*
   dbutils 使用哪个结果集
   BeanHandler         查询结果一个JavaBean
   BeanListHandler     查询结果集是多个JavaBean,存储List集合
   ScalarHandler       单项值查询
   ColumnListHandler   查询一个列数据存储集合List<Object>
*/

Create a User entity class (javabean)

package com.ccc.domain;

public class User {
    private int uid;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Add c3p0 connection pool data, and modify the jdbc path (web02). Add c3p0 Tools

Configure the path in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.ccc.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/mmm</url-pattern>
    </servlet-mapping>
</web-app>

Written page login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录案例</title>
</head>
<body>
    <!--
        action提交服务器的路径
        /web项目某块名/servlet访问的虚拟路径(浏览器输入的地址)
    -->
    <form method="post" action="/web02_login/mmm">
        用户名:<input type="text" name="username" placeholder="请输入用户名"/><br />
        密码:<input type="password" name="password" placeholder="请输入密码"/><br />
        <input type="submit" value="登录"/>
    </form>
</body>
</html>

Writing Server Servlet

package com.ccc.servlet;

import com.ccc.domain.User;
import com.ccc.utils.C3P0UtilsXML;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取表单提交的数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//此处可以加一条输出语句,在控制台输出,用于前期检验是否能获取到username和password
		//System.out.println(username + "\t" + password);
		
		// 作为数据表查询条件
		//创建dbutils工具的 核心类对象 QueryRunner
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		//拼写登录查询的SQL
		String sql = "select * from user where username=? and password=?";
		User user = null;
		try {
			//执行查询语句,获取查询后的结果集BeanHandler
			 user = qr.query(sql,new BeanHandler<User>(User.class),username,password);
		}catch (Exception ex){ex.printStackTrace();}
		//查询后的结果集进行判断
		//条件不匹配,查询不到任何数据,返回null
		if(user==null){
			//查询不到数据,登录失败
			response.getWriter().print("login error");
		}else {
			//查询数据匹配,登录成功
			response.getWriter().print("login success");
		}
	}
}

When the build is complete, run TomCat, the browser will jump to jump to a page. At this point in the final surface mmm virtual address bar added to the address previously set, you will be able to login interface appears.

Guess you like

Origin blog.csdn.net/qq_45083975/article/details/92565920