1、了解servlet的生命周期。
2、数据库表的设计。
3、系统登录用例图
4、页面流程图
5、系统架构图
6、编写类
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
if("login".equals(method)){//登录
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("用户名或密码不能为空!");
return;
}
UserBean userBean = new UserBean();
boolean isValid = userBean.valid(username,password);
if(isValid){
System.out.println("登录成功!");
request.getSession().setAttribute("username", username);
response.sendRedirect("welcome.jsp");
return;
}else{
System.out.println("用户名或密码错误,登录失败!");
response.sendRedirect("login.jsp");
return;
}
}else if ("logout".equals(method)){//退出登录
System.out.println("退出登录!");
request.getSession().removeAttribute("username");
response.sendRedirect("login.jsp");
return;
}else if( "register".equals(method)){//注册
String username = request.getParameter("username");
String password1 = request.getParameter("password1");
String password2 = request.getParameter("password2");
String email = request.getParameter("email");
if(username==null||"".equals(username.trim())||password1==null||"".equals(password1.trim())||password2==null||"".equals(password2.trim())||!password1.equals(password2)){
System.out.println("用户名或密码不能为空!");
response.sendRedirect("register.jsp");
return;
}
UserBean userBean = new UserBean();
boolean isExit = userBean.isExist(username);
if(!isExit){
userBean.add(username, password1, email);
System.out.println("注册成功,请登录!");
response.sendRedirect("login.jsp");
return;
}else{
System.out.println("用户名已存在!");
response.sendRedirect("register.jsp");
return;
}
}
}
}
7、配置web.xml文件
8、编写数据库的Javabean(包括连接、查询、增加、删除、修改等)和用户相关信息的userbean 【可根据自己的理解动态编写】
9、登录页面的form表单中
在action中传入method参数,可以让servlet根据method值选择登录、注册、注销等功能。例如:<form action="UserServlet?method=login" method="post"> 其中,UserServlet为web.xml中配置的servlet-name
其他类似。