基于Myeclipse与MySQL数据库表格的增删改查(后续完善)

本文是基于Myeclipse与MySQL数据库表格的增删改查后续完善部分功能的升级版

注:新增加内容:

(1)在查看完学生个人信息表后可退出并返回到主表;

(2)增加登录界面(附验证码)

一、新增信息


(1)logoutServlet.java

package com.microsofti.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import day03_inport.StudentDao;
import day03_student.Student;

public class LogoutServlet extends HttpServlet {

	private StudentDao dao = new StudentDao();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");	
		List<Student> list = dao.queryAll();
		request.setAttribute("students", list);
		//跳转回列表页面
		request.getRequestDispatcher("list.jsp").forward(request, response);	
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        this.doGet(request, response);
	}
}

(2)UserServlet.java

package com.microsofti.servlet;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取表单提交的数据
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		
		if("lxd".equals(uname) && "123".equals(upwd)) {
			//获取是否保存用户名密码
			String daylength = request.getParameter("daylength");
			if(daylength != null && !daylength.equals("-1")){
				//保存
				int day = Integer.parseInt(daylength);
				Cookie cname = new Cookie("username", uname);
				Cookie cpwd = new Cookie("userpwd",upwd);
				//设置保存时间
				cname.setMaxAge(day*24*3600);
				cpwd.setMaxAge(day*24*3600);
				//添加到response
				response.addCookie(cname);
				response.addCookie(cpwd);
			}
			//将用户名保存在session中
			HttpSession session = request.getSession();
			session.setAttribute("currName", uname);
			//将用户名保存在request中
			request.setAttribute("abc", uname);
			//登录人数+1
			ServletContext sc = this.getServletContext();
			Integer count = (Integer)sc.getAttribute("count");
			if(count != null){
				count++;
			}else{
				count=1;
			}
			sc.setAttribute("count",count);
			//跳转到成功页面
//			response.sendRedirect("success.jsp");
			request.getRequestDispatcher("MyJsp.jsp").forward(request, response);
		}else{
			//跳转到失败页面
			response.sendRedirect("inner.jsp");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}


}

(3)image.jsp(自动刷新验证码)

<%@ page contentType="image/JPEG"  
    import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"  
    pageEncoding="GBK"%>  
<%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜色   
        Random random = new Random();   
        if (fc > 255)   
            fc = 255;   
        if (bc > 255)   
            bc = 255;   
        int r = fc + random.nextInt(bc - fc);   
        int g = fc + random.nextInt(bc - fc);   
        int b = fc + random.nextInt(bc - fc);   
        return new Color(r, g, b);   
    }%>  
<%   
    //设置页面不缓存   
    response.setHeader("Pragma", "No-cache");   
    response.setHeader("Cache-Control", "no-cache");   
    response.setDateHeader("Expires", 0);   

    // 在内存中创建图象   
    int width = 60, height = 20;   
    BufferedImage image = new BufferedImage(width, height,   
            BufferedImage.TYPE_INT_RGB);   

    // 获取图形上下文   
    Graphics g = image.getGraphics();   

    //生成随机类   
    Random random = new Random();   

    // 设定背景色   
    g.setColor(getRandColor(200, 250));   
    g.fillRect(0, 0, width, height);   

    //设定字体   
    g.setFont(new Font("Times New Roman", Font.PLAIN, 18));   

    //画边框   
    //g.setColor(new Color());   
    //g.drawRect(0,0,width-1,height-1);   

    // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到   
    g.setColor(getRandColor(160, 200));   
    for (int i = 0; i < 100; i++) {   
        int x = random.nextInt(width);   
        int y = random.nextInt(height);   
        int xl = random.nextInt(12);   
        int yl = random.nextInt(12);   
        g.drawLine(x, y, x + xl, y + yl);   
    }   

    // 取随机产生的认证码(4位数字)   
    String sRand = "";   
    for (int i = 0; i < 4; i++) {   
        String rand = String.valueOf(random.nextInt(10));   
        sRand += rand;   
        // 将认证码显示到图象中   
        g.setColor(new Color(20 + random.nextInt(110), 20 + random   
        .nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成   
        g.drawString(rand, 13 * i + 6, 16);   
    }   

    // 将认证码存入SESSION   
    session.setAttribute("code", sRand);   

    // 图象生效   
    g.dispose();   

    // 输出图象到页面   
    ImageIO.write(image, "JPEG", response.getOutputStream());   
%>

(4)inner.jsp修改

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

//判断session是否有用户名
String name = (String)session.getAttribute("currName");
if(name == null){
	//保存错误信息
	request.setAttribute("errmsg", "用户名/密码错误,请重新登录!");
	//跳转回登录页面
	request.getRequestDispatcher("login.jsp").forward(request, response);
}
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>登录页面失败!</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <div style="color:red;">登录页面失败!</div>
  </body>
</html>

(5)index.jsp修改

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

//获取全部cookie
Cookie[] cookies = request.getCookies();

String name = null,pwd = null;
//遍历
for(Cookie c : cookies){
	if(c.getName().equals("username")){
		//获取用户名
		name = c.getValue();
	}
	if(c.getName().equals("userpwd")){
		//获取密码
		pwd = c.getValue();
	}
}
if(name != null && pwd != null){
	//登录
	request.getRequestDispatcher("myservlet?uname="+name+"&upwd="+pwd).forward(request, response);
}

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

(6)login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript">
    function reImg() {
        var img = document.getElementById("Img");
        img.src = "image.jsp?code=" + Math.random();
    }
	</script>
	<style>
    #main{
		width:100%;
		height:100%; position:absolute; left:50%; top:50%; margin-left:-150px; margin-top:-100px;
		
}
    </style>
<body>
  </head>
  
  <body>
  <div id="main">
  <span style="font-size: 3em">用户登录/LOGIN</span> <br>
  -----------------------------------------------------------
  <div style="color:red;">${errmsg }</div>
  <form action="UserServlet" method="post">
	    <table style="padding-left: 1em;">
                <tr>
                    <td>用户名:</td>
                    <td><input type=text name=uname />
                    </td>
                </tr>
                <tr>
                    <td>密   码:</td>
                    <td><input type="password" name="upwd" />
                    </td>
                </tr>
                <tr>
                    <td>验证码:</td>
                    <td><input type="text" name="yanzhengma" /><img border=0
                        id="Img" src="image.jsp" alt="验证码"><a href="#"
                        onclick="reImg();">看不清,请点击刷新</a>
                    </td>
                </tr>
            </table>
            <table style="padding-left: 0.6em">
                <tr>
                    <td><input type=radio name=type value=partment>部门 <input
                        type=radio name=type value=teacher>教师 <input type=radio
                        name=type value=student checked>学生 <input type=radio
                        name=type value=guest>访客</td>
                </tr>
                
                <tr>
                    <td>
                    	 保存密码时间:<select name="daylength">
				    	<option value="-1">请选择</option>
				    	<option value="3">3天</option>
				    	<option value="7">7天</option>
				    	<option value="30">30天</option>
				    </select>
				    <br><br>
				    <input type="submit" value="登录" /> <input type="reset"
			                        value="重置" />
                    </td>
                </tr>
            </table>
    </form></div>
  </body>
  
</html>

(7)MyJsp.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page  import="java.io.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <h2>查看学生基本情况表</h2> 
    <a href="Listservlet" >
    	<button>查看</button>
    	</a>
  </body>
</html>

(8)view.jsp修改

<%@page import="day03_student.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="day03_inport.StudentDao"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>学生个人信息</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
	table{
	border:1px solid gray;
	border-collapse:collapse;
	width:50%
	}
	td{
	border:1px solid gray;
	}
	</style>
  </head>
  
  <body>
    <h2>学生个人基本信息</h2>
    <form action="LogoutServlet" method="post">
   <table>
   <tr>
    <td>编号</td>
    <td>学号</td>
    <td>姓名</td>
    <td>性别</td>
    <td>年龄</td>
    </tr> 
     <tr>
      <%
		Student s=(Student)request.getAttribute("students");
	 %>
     <td><%=s.getId()%></td>
     <td><%=s.getStuno()%></td>
     <td><%=s.getName()%></td>
     <td><%=s.getGender()%></td>
     <td><%=s.getAge() %></td>
     </tr>
  
   </table><br>
   <button type="submit" >退出</button>
   </form>
  </body>
</html>

二、新增样式:

(1)登录界面


登录失败:


登录成功后的显示:


(2)查看个人信息后退出


点击退出后结果



猜你喜欢

转载自blog.csdn.net/myclass1312/article/details/80790087