JSP+Servlet+MySQL实现登录功能

学习Java一段时间,想着用Java写一个最简单的登录程序。

首先是需求分析,最简单的登录功能即可。

用MVC思想分析一下,大致需要JSP(页面展示)+Model(数据对接)+Servlet(控制层)。

准备:创建数据库

MySQL+Navicat(可选)

创建用户表,因为不加注册功能,所以直接在表中写入用户名和密码即可。

一、View层

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>logintitle>
  head>
  <body>
  <h2>用户登录界面h2>
  <form method="post" action="loginServlet">
    用户名:<input type="text" name="username"/>
    密码:<input type="password" name="password"/>
    <input type="submit" value="登录"/>
  form>
  body>
html>

简单的页面展示即可,由jsp也可得到,需要写一个loginServlet即可。

二、Model层

因为此处功能极其简单,也就不需要分Dao层、Service层、Pojo层等,写一个数据库连接即可。

import java.sql.*;

public class DBConn {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/dbname"; 
    static final String USER = "";
    static final String PASSWORD = "";

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //打开连接
    public Connection getConn() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭连接
    public void closeConn(ResultSet rs,PreparedStatement ps,Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("Database is closed.");
    }

    //查询语句
    public int query(String sql,String []param) {
        int count = 0;
        try {
            this.getConn();
            ps = conn.prepareStatement(sql);//防止sql注入,使用prepareStatement
            if(param != null){
                for (int i = 0; i < param.length; i++) {
                    ps.setString(i + 1, param[i]);
                }
            }
            rs = ps.executeQuery();
             while(rs.next()){
                 count = rs.getInt(1);
             }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeConn(rs,ps,conn);
        }
        return count;
    }
}
此处没有增删改相关的操作,只写了查询这一项功能,需要可以添加上。

三、Controller层

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class loginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset = GBK");
        PrintWriter out = response.getWriter();
        // 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        DBConn dbConn = new DBConn();
        String sql = "SELECT COUNT(1) FROM user WHERE username = ? AND password = ?";
        int count = dbConn.query(sql,new String[]{username,password});
        if(count == 0){
            out.print("用户名或密码错误");
            out.print("
请重新登陆"); }else{ out.println("登录成功"); //获取session,并将用户名和密码保存在session HttpSession session = request.getSession(); session.setAttribute("username", username); session.setAttribute("password", password); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
注:初学者,记录一下学习过程,如有错误请海涵。

你可能感兴趣的:(Java)