Servlet(二)

2020-02-20 21:02:00
java - servlet - web

先前写了一篇servlet基础,简单的理解了一下javaweb的基础内容,趁着放假没事自己利用servlet与jdbc编写一个登录示例进一步巩固基础,项目的目录结构如下:

可能不太标准,毕竟目前仍然处于学习中。

数据库功能

先create一个数据库loginservlet,然后设计一个表:

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `uname` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `pwd` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) 

简单的放入id、uname、pwd三个字段,以id作为主键,然后在其内插入一个用户以便后续测试:

INSERT INTO 'user' (id,uname,pwd) VALUES (1,"admin","admin");

关于数据库的用户名密码等数据我使用properties文件作为存储:

DRIVER=com.mysql.cj.jdbc.Driver
URL=jdbc:mysql://localhost:3306/loginservlet?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
USER=root
PASSWD=root

我用jdbc自己写了一个简单的jdbc工具类以便后续操作数据库:

package Jdbc.pa;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUntil {
    static Properties pro = null;
    static {
        pro = new Properties();
        try {
            pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected static final String DRIVER = pro.getProperty("DRIVER");
    protected static final String URL = pro.getProperty("URL");
    protected static final String USER = pro.getProperty("USER");
    protected static final String PASSWD = pro.getProperty("PASSWD");

    public static Connection getConn(){
        Connection connection = null;
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL,USER,PASSWD);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            return connection;
        }
    }
}

事实上,可以将close方法也全部放入一个方法中,这样更加方便。

登录功能

首先是登录界面放入一个表单:

<form method="post" action="/ServletDemo01_war_exploded/loginServlet">
    <label>name</label>
    <input name="uname">
    <br>
    <label>passwd</label>
    <input name="pwd">
    <button type="submit">提交</button>
</form>

每当用户提交表单时会将uname和pwd的值提交给后端,接下来就是后端的servlet类:

package Servlet.pa;

import Func.pa.LoginUntil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        if(LoginUntil.login(uname,pwd)==1){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

直接在doGET中调用doPOST,这样相同的代码就只需要写一份了。

将前段传来的两个值传入LoginUntil.login中,其内代码如下:

package Func.pa;

import Jdbc.pa.JdbcUntil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginUntil {
    private String uname;
    private String pwd;

    public String getUname() {
        return uname;
    }

    public String getPwd() {
        return pwd;
    }

    public static int login(String uname,String pwd){
        Connection connection = JdbcUntil.getConn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from user where uname=? and pwd=?";
        int resilt = 0;
        System.out.println(connection);
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,uname);
            ps.setString(2,pwd);
            rs = ps.executeQuery();
            if(rs.first()==true){
                resilt = 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return resilt;
        }
    }
}

数据库连接处使用prepareStatement做预编译防止sql注入。

至此登录功能就实现了。



本文原创于HhhM的博客,转载请标明出处。



CopyRight © 2019-2020 HhhM
Power By Django & Bootstrap
已运行
粤ICP备19064649号