本文是基于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