简封为HttpServlet的用户登录例子、结合jdbc的用户登录例子

我们先看简封为HttpServlet的用户登录例子

这个小例子对servlet、request进行了小小的封装
需求是:在web.xml中进行配置用户名、密码,然后通过html进行登录,跳转到servlet,通过getServletContext().getInitParameter获取配置信息,然后通过req.getParameter获取请求信息,如果用户名、密码配对正确那么就输出成功即可

首先看配置文件:

    
    <context-param>
        <param-name>userparam-name>
        <param-value>wyfparam-value>
    context-param>
    <context-param>
        <param-name>passwordparam-name>
        <param-value>123456param-value>
    context-param>
   <servlet>
    <servlet-name>loginServletservlet-name>
    <servlet-class>com.safly.LoginServlet2servlet-class>
  servlet>

  <servlet-mapping>
    <servlet-name>loginServletservlet-name>
    <url-pattern>/loginServleturl-pattern>
  servlet-mapping>


然后看一个简单的html界面login.html


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
    <form action="loginServlet" method="post">
        user:<input type="text" name="user" /> 
        password:<input type="text"
        <input type="submit" value="Submit" />
    form>
body>
html>

MyGenericServlet

package com.safly;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public abstract class MyGenericServlet implements Servlet, ServletConfig {
    public void destroy() {

    }
    public ServletConfig getServletConfig() {
        return servletConfig;
    }
    public String getServletInfo() {
        return null;
    }
    private ServletConfig servletConfig;
    public void init(ServletConfig config) throws ServletException {
        this.servletConfig = config;
        init();
    }
    private void init() throws ServletException {

    }
    public abstract void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException;

    //以下是ServletConfig的实现方法
    public String getInitParameter(String arg0) {
        return servletConfig.getInitParameter(arg0);
    }
    public Enumeration getInitParameterNames() {
        return servletConfig.getInitParameterNames();
    }
    public ServletContext getServletContext() {
        return servletConfig.getServletContext();
    }
    public String getServletName() {
        return servletConfig.getServletName();
    }
}

MyHttpServlet

package com.safly;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyHttpServlet extends MyGenericServlet {
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        if (req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) req;
            if (res instanceof HttpServletResponse) {
                HttpServletResponse response = (HttpServletResponse) res;
                service(request, response);
            }
        }
    }

    public void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String method = req.getMethod();
        if ("GET".equalsIgnoreCase(method)) {
            doGet(req, res);
        } else if ("POST".equalsIgnoreCase(method)) {
            doPost(req, res);
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException {

    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {

    }
}

LoginServlet2

package com.safly;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet2 extends MyHttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        String username = req.getParameter("user");
        String password = req.getParameter("password");

        String initUser = getServletContext().getInitParameter("user");
        String initPassword = getServletContext().getInitParameter("password");

        PrintWriter pw = res.getWriter();
        if (initUser.equals(username) && initPassword.equals(password)) {
            pw.print("Helloo:" + username);
        } else {
            pw.print("Sorryy:" + username);
        }
    }
}


进行调试:
http://localhost:8080/day01/login.html
输入wyf,123456
然后浏览器输出 Helloo:wyf 说明校验正确
如果输出错误输出 Sorryy:www(用户名输入的是www)
http://localhost:8080/day01/loginServlet

结合jdbc的用户登录例子
总体流程就是创建一个user数据库,里面存有用户登录的姓名、密码
然后通过html页面进行登录,跳转到servlet,通过req.getParameter获取对应的值,构建sql语句,jdbc进行数据库链接,去查询数据库是否有用户信息,如果有的话,就输出登录成功即可

简封为HttpServlet的用户登录例子、结合jdbc的用户登录例子_第1张图片
以上就是创建mydatabase数据库,然后创建user表,字段有username、password

再看代码之前,由于jdbc是数据库连接池,所以有些方法需要用到mysql-connector-java-5.1.7-bin.jar
直接丢在WEB-INF-lib下即可


我们还是先来看web.xml配置信息:

    
    <servlet>
        <servlet-name>loginServletservlet-name>
        <servlet-class>com.safly.LoginServelt3servlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>loginServletservlet-name>
        <url-pattern>/loginServleturl-pattern>
    servlet-mapping>

接下来就就看html界面的东东,就一个用户名,密码框

"loginServlet" method="post"> user:type="text" name="username" /> password:type="text" name="password" />
type="submit" value="Submit" />

然后就是servlet了

package com.safly;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServelt3 extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username:"+username+",password:"+password);

        java.sql.Connection connection = null;
        java.sql.PreparedStatement statement = null;
        ResultSet resultSet = null;

        PrintWriter pw = resp.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/mydatabase";
            String user = "root";
            String password2 = "root";
            connection = DriverManager.getConnection(url, user, password2);


            String sql = "select count(id) from user where username=? and password=?";

            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);

            resultSet = statement.executeQuery();


            if (resultSet.next()) {
                int count = resultSet.getInt(1);
                System.out.println("resultSet.count1:"+count);
                if (count == 1) {
                    pw.print("hello" + username);
                } else {
                    pw.print("sorry" + username);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

浏览器调试:
http://localhost:8080/day01/login.html
输入wyff、wyf
简封为HttpServlet的用户登录例子、结合jdbc的用户登录例子_第2张图片

这说明wyff、wyf在数据库中存在2条记录
这里判断的不严禁

if (count == 1) {
                    pw.print("hello" + username);
                } else {
                    pw.print("sorry" + username);
                }

就输出 sorrywyff

你可能感兴趣的:(Javaee-javaweb)