全网最使用MySQL, JSP, Bean, JDBC(连接数据库) ,制作有权限(老师,学生,辅导员) 用户登录demo,表单查看demo

1.准备相关数据,创建数据库(Lab_db)

create database Lab_DB DEFAULT CHAR SET utf8;  /*创建数据库Lab_db*/
use Lab_DB;                                     /*使用数据库Lab_db*/
/*创建表结构*/
create table user(id_user int not null auto_increment,account varchar(10)not null,
password varchar(10)null,username varchar(10)null,gender varchar(2)null ,
department varchar(20)null,access_rights varchar(10),primary key (id_user));

2.写入测试数据

insert into user(account, password, username, gender, department, access_rights)
values('demo005','007','小wa哥','男','技术','老师');
insert into user(account, password, username, gender, department, access_rights)
values('demo006','007','小wa哥','女','计算机','辅导员');
insert into user(account, password, username, gender, department, access_rights)
values('demo008','007','小wa哥','男','技术','辅导员');
insert into user(account, password, username, gender, department, access_rights)
values('demo009','007','小wa哥','男','技术','老师');
insert into user(account, password, username, gender, department, access_rights)
values('demo001','007','小wa哥','男','技术','老师');
insert into user(account, password, username, gender, department, access_rights)
values('demo002','007','小wa哥','男','技术','老师');
select * from user;

目录结构

  • bean.demo
    • ContentBean
    • dataBean
  • JDBC(用于测试数据库连接是否成功!)
    • JDBCdemo
  • servlet.demo
    • deleteDemo
    • updataDemo
    • registerDemo
  • WEB
    • index.html
    • conentbeanDemo.jsp
    • user.html

ConnectBean.java

package bean.demo;

import java.sql.Connection;
import bean.demo.dataBean;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectBean {
       //数据库信息
        String url = "jdbc:mysql://localhost:3306/Lab_DB"; 
        String user = "root";   
        String pwd = "admin"; 
      
        private Connection conn;  //连接
        private Statement stmt_select;     //SQL语句
        private Statement stmt_delete;
        private Statement stmt_update;
        private Statement stmt_insert;
        ResultSet rs;            //结果集
        
       
            
        //实例化JavaBean对象的同时创建数据库连接
   public  ConnectBean() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection(url,user,pwd);
        }catch(Exception e) {
            e.printStackTrace();  
        }
   }
     

    public String access(String account) throws SQLException {
       
      //"学生“权限只显示单个记录,其他权限显示所有记录;      
       String sql = "select * from user where account='"+account+"'";
       dataBean test=new dataBean();
       ResultSet rs=selectSql(sql);
       
          if(rs.next() ) {
              //System.out.println(rs.getString("access_rights"));
              test.setAccess_rights(rs.getString("access_rights"));
          
             switch(rs.getString("access_rights")) {
                case "学生":break;
                default: sql="select * from user";            
             }
             
          }
          return sql;
       
    }
    
    //查询记录
    public ResultSet selectSql(String sql) {
       
       try {
           stmt_select=conn.createStatement();
           rs = stmt_select.executeQuery(sql);
       }catch(SQLException e) {
           e.printStackTrace();   
       }
       
      return rs;       
       
    }
    
    //添加记录
    public int insertSql(String sql) {
       
       try {
           stmt_insert=conn.createStatement();
           return stmt_insert.executeUpdate(sql); 
       }catch(SQLException e) {
           e.printStackTrace();   
       }
      return 0;

     } 
    //删除记录
 public int deleteSql(String sql) {
   
   try {
       stmt_delete=conn.createStatement();
       return stmt_delete.executeUpdate(sql); 
   }catch(SQLException e) {
       e.printStackTrace();   
   }
  return 0;

 } 
 //更新记录
 public int updateSql(String sql) {
   
   try {
       stmt_update=conn.createStatement();
       return stmt_update.executeUpdate(sql);  
   }catch(SQLException e) {
       e.printStackTrace();   
   }
   
      return 0;        
   
 }
 
 //关闭数据库连接
    public void closeConn() {
       try {
           if(conn!=null)   
               conn.close();
       }catch(SQLException e) {
           e.printStackTrace();   
       }
      
    }
  
}


dataBean

package bean.demo;

public class dataBean {
   //定义成员变量
   private int id_user;
   private String account;
   private String password;
   private String username;
   private String gender; 
   private String department;
   private String access_rights; 
   
   public dataBean() {
    
   }
   
   public dataBean(int id_user, String account, String password, String username, String gender, String department,
     String access_rights) {
    super();
    this.id_user = id_user;
    this.account = account;
    this.password = password;
    this.username = username;
    this.gender = gender;
    this.department = department;
    this.access_rights = access_rights;
   }
   
   
   public int getId_user() {
    return id_user;
   }
   public void setId_user(int id_user) {
    this.id_user = id_user;
   }
   public String getAccount() {
    return account;
   }
   public void setAccount(String account) {
    this.account = account;
   }
   public String getPassword() {
    return password;
   }
   public void setPassword(String password) {
    this.password = password;
   } 
   public String getUsername() {
    return username;
   }
   public void setUsername(String username) {
    this.username = username;
   }
   public String getGender() {
    return gender;
   }
   public void setGender(String gender) {
    this.gender = gender;
   }
   public String getDepartment() {
    return department;
   }
   public void setDepartment(String department) {
    this.department = department;
   }
   public String getAccess_rights() {
    return access_rights;
   }
   public void setAccess_rights(String access_rights) {
    this.access_rights = access_rights;
   }
      
  }
   
  

JDBCdemo.java

package JDBCdemo;
import java.sql.Connection;
import java.sql.DriverManager;

public class jdbcdemo {
  public static void main(String args[]){
      try {
          Class.forName("com.mysql.cj.jdbc.Driver");
          System.out.println("成功加载mysql数据库驱动程序!");
      }
      catch(Exception e) 
      {
          System.out.println("加载sql程序时出现错误!");
          e.printStackTrace();
          
      }
      try {
          //链接数据库
          Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/lab_db","root","admin");
          System.out.println("成功连接数据库!");
      }
      catch(Exception e){
          System.out.println("连接数据失败!");
          e.printStackTrace();
      }
  }

}


deleteDemo.java

package servlet.demo;

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

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 bean.demo.ConnectBean;
import java.sql.*;

@WebServlet("/deleteDemo")

public class deleteDemo extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
  ConnectBean conn=new ConnectBean();

 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
      String sql="delete from user where "+request.getQueryString();  
      conn.deleteSql(sql);
        response.sendRedirect("connectbeanDemo.jsp");
  }


  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      doGet(request, response);
  }

}


registerDemo

package servlet.demo;

import java.io.IOException;
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 bean.demo.ConnectBean;


@WebServlet("/registerDemo")

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

  ConnectBean conn=new ConnectBean();
    
    
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
      request.setCharacterEncoding("UTF-8");
      String account=request.getParameter("account");
      String password=request.getParameter("password");
      String username=request.getParameter("username");
      String gender=request.getParameter("gender");
      String department=request.getParameter("department");
      String access_rights=null;
      
      //对不同的部门赋予不同的权限
       switch(department){
       case "信息部": access_rights="系统管理员";break;
       case "教务部": access_rights="老师";break;
       case "辅导员": access_rights="辅导员";break;
       default: access_rights="学生";
       }
      
      String sql="insert into user(account,password,username,gender,department,access_rights) values(\'"+account+"\',\'"+password+"\',\'"+username+"\',\'"+gender+"\',\'"+department+"\',\'"+access_rights+"\')";
   //  System.out.println(sql);
      conn.insertSql(sql);
       // response.sendRedirect("connectbeanDemo.jsp");
        response.sendRedirect("index.html");
  }


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

}


updateDemo

package servlet.demo;

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

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 javax.servlet.http.HttpSession;
import javax.websocket.Session;

import bean.demo.ConnectBean;
import java.sql.*;

@WebServlet("/updateDemo")
public class updateDemo extends HttpServlet {

  private static final long serialVersionUID = 1L;
  
  ConnectBean conn=new ConnectBean();

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
          PrintWriter out=response.getWriter();
          HttpSession session=request.getSession(); 
          
 if(request.getParameter("update_submit")==null) {
   
    session.setAttribute("whereClause",request.getQueryString());  
    
     out.println("<!DOCTYPE html><html>");
     out.println("<form action=\"updateDemo\" method=\"get\">");
     out.println("<label>用户:</label>");
     out.println("<input type=\"text\" name=\"username\"/><br>");
     out.println("<label>性别:</label>");
     out.println("<select name='gender'>");
     out.println("<option>男</option>\n");
     out.println("<option>女</option>\n");
     out.println("</select><br>");
     out.println("<label>所属部门:</label>");
     out.println("<select name='department'>");
     out.println("<option>1班</option>\n");
     out.println("<option>2班</option>\n");
     out.println("<option>3班</option>\n");
     out.println("<option>4班</option>");
     out.println("<option>辅导员</option>");
     out.println("<option>信息部</option>");
     out.println("<option>教务部</option>");
     out.println("</select><br><br>");
     out.println("<input type=\"submit\" name=\"update_submit\" value=\"提交修改\"/><br>\n"+ "</form></html>");
     
    }else {   
         //根据“所属部门”,赋于对应权限
        String access_rights;
        switch(request.getParameter("department")) {
           case "信息部": access_rights="系统管理员";break;
           case "教务部": access_rights="老师";break;
           case "辅导员": access_rights="辅导员";break;
           default: access_rights="学生";
       }
     String sql="update user set username=\""+request.getParameter("username")+"\", gender=\""+request.getParameter("gender")+"\",department=\""+request.getParameter("department")+"\",access_rights=\""+access_rights+"\"  where "+ session.getAttribute("whereClause");
      // System.out.println(sql);
        conn.updateSql(sql);
         response.sendRedirect("connectbeanDemo.jsp");  
     }  
  
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      doGet(request, response);
  }

}


connectionbeanDemo.JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@page import="bean.demo.ConnectBean"%>
<%@page import="bean.demo.dataBean"%>
<%@page import="java.io.IOException"%>
<%@page import="java.sql.*"%>
<%@ page import="java.sql.Connection"%>

  
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
 <jsp:useBean id="data" class="bean.demo.dataBean" scope="session"/>
 <jsp:useBean id="connect" class="bean.demo.ConnectBean" scope="session"/>
<%  
String sql;

if(request.getParameter("login_submit")!=null) {
  sql=connect.access(request.getParameter("account"));
 
}else sql="select * from user";

System.out.println(sql);
ResultSet rs=connect.selectSql(sql);

%>
<table border="1" width="800">
<tr>
  <td width="100" align="center">ID</td>
   <td width="200" align="center">用户</td>
   <td width="200" align="center">性别</td>
   <td width="200" align="center">所在班级</td>
   <td width="200" align="center">权限</td>
    <td width="400" align="center">操作</td>   
</tr>

<%  while(rs.next()){    %>   

  <tr>
   <td width="100" align="center"><%=rs.getInt("id_user")%></td>
     <td width="200" align="center"><%=rs.getString("username")%></td>
     <td width="200" align="center"><%=rs.getString("gender")%></td>
     <td width="200" align="center"><%=rs.getString("department")%></td>
     <td width="200" align="center"><%=rs.getString("access_rights")%></td>
     <td align="center"><a href="updateDemo?id_user=<%=rs.getInt("id_user") %>" >修改</a>
        <a href="deleteDemo?id_user=<%=rs.getInt("id_user") %>" onclick="return confirm('确定将此记录删除?')">删除</a>
     </td>    
   </tr>
<% }   %>


</table>

<input type="button" value="返回首页" onclick="{location.href='index.html'}" />
<input type="button" value="新增记录" onclick="{location.href='user.html'}" />

</body>
</html>

index.html

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
   
<%@page import="bean.demo.ConnectBean"%>
<%@page import="bean.demo.dataBean"%>
<%@page import="java.io.IOException"%>
<%@page import="java.sql.*"%>
<%@ page import="java.sql.Connection"%>

 
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="data" class="bean.demo.dataBean" scope="session"/>
<jsp:useBean id="connect" class="bean.demo.ConnectBean" scope="session"/>
<%  
String sql;

if(request.getParameter("login_submit")!=null) {
 sql=connect.access(request.getParameter("account"));

}else sql="select * from user";

System.out.println(sql);
ResultSet rs=connect.selectSql(sql);

%>
<table border="1" width="800">
<tr>
 <td width="100" align="center">ID</td>
  <td width="200" align="center">用户</td>
  <td width="200" align="center">性别</td>
  <td width="200" align="center">所在班级</td>
  <td width="200" align="center">权限</td>
   <td width="400" align="center">操作</td>   
</tr>

<%  while(rs.next()){    %>    

 <tr>
   <td width="100" align="center"><%=rs.getInt("id_user")%></td>
    <td width="200" align="center"><%=rs.getString("username")%></td>
    <td width="200" align="center"><%=rs.getString("gender")%></td>
    <td width="200" align="center"><%=rs.getString("department")%></td>
    <td width="200" align="center"><%=rs.getString("access_rights")%></td>
    <td align="center"><a href="updateDemo?id_user=<%=rs.getInt("id_user") %>" >修改</a>
       <a href="deleteDemo?id_user=<%=rs.getInt("id_user") %>" onclick="return confirm('确定将此记录删除?')">删除</a>
    </td>    
  </tr>
<% }   %>


</table>

<input type="button" value="返回首页" onclick="{location.href='index.html'}" />
<input type="button" value="新增记录" onclick="{location.href='user.html'}" />

</body>
</html>

user.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form  action = "registerDemo" method = "get">


  学号/工号:<input type="text" name="account"/><br>
  密码:<input type = "text" name = "password"/> <br>
  用户名:<input type = "text" name = "username"/> <br>
  性别:<input type = "text" name = "gender"/> <br>
  所在班级:<input type = "text" name = "department"/> <br>
  权限:<input type = "text" name = "access_rights"/> <br>
     <input name="Submit" type="submit" value="添加" onclick=getParameter>
</form>

</body>
</html>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容

  • JAVA面试题 1、作用域public,private,protected,以及不写时的区别答:区别如下:作用域 ...
    JA尐白阅读 1,143评论 1 0
  • 一. Java基础部分.................................................
    wy_sure阅读 3,785评论 0 11
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,567评论 18 399
  • 1、不安全的随机数生成,在CSRF TOKEN生成、password reset token生成等,会造成toke...
    nightmare丿阅读 3,673评论 0 1
  • 小编费力收集:给你想要的面试集合 1.C++或Java中的异常处理机制的简单原理和应用。 当JAVA程序违反了JA...
    八爷君阅读 4,568评论 1 114