使用Servlet实现简单的用户管理

一、Servlet作用

Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
使用 Servlet,您可以收集来自网页表单的用户输入,呈现来自数据库或者其他源的记录,还可以动态创建网页。

二、具体实现

文件目录:

在这里插入图片描述
注:idea创建web工程,若想出现meta-inf,如下操作
在这里插入图片描述

1.注册页面(默认pom.xml已添加依赖)
暂时采用比较原始的form界面,后续将会使用easy ui 进行美观处理。代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>login.html</title>
  <style type="text/css">
  </style>
</head>
<body>
<h1>用户登录</h1>
<form action="http://127.0.0.1:8080/InternshipProject_war/login.emp" method="post">
  用户名:<input type="text" name="userName"><br>
  密码:<input type="password" name="password"><br>
  <input type="submit" value="登录">
</form>
<%
  Object obj=request.getAttribute("msg");
  if(obj!=null){
%>
<span style="color: red;"><%=obj.toString() %></span>
<%
  }
%>
</body>
</html>

2.创建实体类(注意序列化)
序列化原因

package entity;

import java.io.Serializable;

public class Emp implements Serializable {
  private String name;
  private String sex;
  private String edu;

  public Emp() {
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }

  public String getEdu() {
    return edu;
  }

  public void setEdu(String edu) {
    this.edu = edu;
  }
}

3.数据库测试连接
使用 pom.xml进行导入

  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>

4.servlet实现

servlet类

package servlets;

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.io.UnsupportedEncodingException;
import java.sql.*;
import java.text.DateFormat;
import java.util.Date;

public class EmpServlet extends HttpServlet {


  static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost:8889/emp";//端口号默认3306 ,本人采用集成所以端口号不一样
  static final String USER = "你的用户名";
  static final String PASS = "你的密码";

  public  static void main(String[] args) throws SQLException, ClassNotFoundException {
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response){


  }
// post处理
  protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    String path = request.getServletPath();
    if("/login.emp".equals(path)){
      try {
        login(request,response);
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }

  }

  private  Connection connect() throws ClassNotFoundException, SQLException {
    Connection conn = null;
    Statement stmt = null;

    // 注册JDBC
    Class.forName(JDBC_DRIVER);
    // 打开链接
    System.out.println("连接数据库...");
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    return conn;
  }


  // 员工登录
  protected void login(HttpServletRequest request,HttpServletResponse response) throws SQLException, ClassNotFoundException, ServletException, IOException {
    System.out.println("登录中...");
    String userName =request.getParameter("userName");
    String password =request.getParameter("password");

    System.out.println("采集的password:"+password);
    System.out.println("采集的userName:"+userName);

    Statement statement = connect().createStatement();
    ResultSet rs = statement.executeQuery("select * from empinfo");

    while(rs.next()){
//      System.out.println(rs.getString("password"));
      if(password.equals(rs.getString("password"))&&userName.equals(rs.getString("userName"))){
        Date date = new Date();
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
        System.out.println(userName+"于"+df.format(date)+"登录成功");
        request.getRequestDispatcher("jsp/index.jsp").forward(request, response);;
        return;
    }
      Date date = new Date();
      DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
      System.out.println(userName+"于"+df.format(date)+"登录失败");
      //		如果登录失败,控制台输出用户名密码不正确
      System.out.println("用户名密码不正确");

//		将需要转发的信息放入request请求对象中
      request.setAttribute("msg", "用户名密码不正确");
//		通过请求转发技术将错误信息传递给login.jsp页面做显示
//								工程内部的资源路径
      request.getRequestDispatcher("/jsp/login/login.jsp").forward(request, response);
    }
  }
}

web.xml进行配置

 <servlet>
    <servlet-name>Emp</servlet-name>
    <servlet-class>servlets.EmpServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Emp</servlet-name>
    <url-pattern>*.emp</url-pattern>
  </servlet-mapping>

其他:

request.getRequestDispatcher()和response.sendRedirect()区别
日期的使用

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值