JSP一个理解MVC架构的简单的登陆、注册例子

首先我们看看这个目录结构


--+login
----------+WEB-INF
-----------------------+classes
-beans
-tags
-----------+tlds

login 是主目录放jsp文件,在例子login.jsp,loginFailed.jsp,login_form.jsp,newAccount.jsp,welcome.jsp,accountCreated.jsp

Web-inf下面有web.xml配置文件,classes文件夹放类,tlds文件夹放自定义标签
由于我没有用到数据库,所以没有用LIB文件夹,是来放置*.jar文件的。

classes目录下,有beans,tags文件夹,分别放置User,LoginDB类,和自定义标签类GetRequestParameterTag,classes目录下还直接放了LoginServlet,NewAccountServlet控制器类


我们先看beans下的两个业务对象类
User.java



package beans;

public class User implements java.io.Serializable {
private final String userName,password,hint;
                //final强调此属性初始化后,不能修改hint是口令提示
public User(String userName,String password,String hint) {
this.userName = userName;
this.password = password;
this.hint = hint;
}
public String getUserName(){
return userName;
}
public String getPassword(){
return password;
}
public String getHint(){
return hint;
}
//判断当前对象用户名和密码是否相等
public boolean equals(String uname,String upwd) {
return getUserName().equals(uname) &&
   getPassword().equals(upwd);
}
}



LoginDB.java



package beans;

import java.util.Iterator;
import java.util.Vector;

public class LoginDB implements java.io.Serializable {
private Vector users = new Vector();
//Vector类是同步的,所以addUser就不需要同步了
public void addUser(String name,String pwd,String hint) {
users.add(new User(name,pwd,hint));
}
//下面方法判断是否存在正确的user
public User getUser(String name,String pwd) {
Iterator it = users.iterator();
User user;
//迭代需要同步
synchronized(users) {
while(it.hasNext()){
user = (User)it.next();
if(user.equals(name,pwd))
return user; //如果返回真,就返回当前user
}
}
return null;
}
public String getHint(String name) {
Iterator it = users.iterator();
User user;
synchronized(users) {
while(it.hasNext()){
user = (User)it.next();
if(user.getUserName().equals(name))
return user.getHint();
}
}
return null;
}
}
login.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Login Page</title>
</head>
<body>
<@ include file="login_form.jsp">
</body>
</html>


被包含的login_form.jsp

<%@ taglib uri="utilities" prefix="util" %>
<!--调用自定义标签,引用为util,uri的utilities在web.xml映射了-->
<p><font color="#6666CC">请登陆</font></p>
<hr>
<form name="form1" method="post" action="<%=response.encodeURL("login")%>"><!--login是LoginSevlet通过在web.xml映射了-->
<table width="68%" border="0" cellpadding="2" cellspacing="2">
<tr>
<td width="33%" align="right">用户名:</td>
<td width="67%">
<input type="text" name="userName" value="<util:requestParameter property='userName'/>"></td><!--注意这里用了自定义标签,如果有值就显示-->
</tr>
<tr>
<td align="right">密码:</td>
<td><input type="text" name="userPwd" ></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" name="Submit" value="登陆">
</td>
</tr>
</table>
</form>


LoginServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

import beans.User;
import beans.LoginDB;

public class LoginServlet extends HttpServlet {
private LoginDB loginDB;

public void init(ServletConfig config) throws ServletException {
super.init(config);
loginDB = new LoginDB();
config.getServletContext().setAttribute("loginDB",loginDB);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
String name = request.getParameter("userName");
//从login_form表单得到值
String pwd = request.getParameter("userPwd");
User user = loginDB.getUser(name,pwd);
if(user != null){ //说明存在用户
request.getSession().setAttribute("user",user);
//放到session里面
request.getRequestDispatcher(response.encodeURL("/welcome.jsp"))
.forward(request,response);
      //成功转发到welcome.jsp
}else{
request.getRequestDispatcher(response.encodeURL("/loginFailed.jsp"))
.forward(request,response);
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}

web.xml添加

<servlet>
<servlet-name>Login</servlet-name><!--名字-->
<servlet-class>LoginServlet</servlet-class><!--指定类-->
</servlet><servlet>
<servlet-name>new_account</servlet-name>
<servlet-class>NewAccountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>new_account</servlet-name>
<url-pattern>/new_account</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Login</servlet-name><!--和上面的名字一致-->
<url-pattern>/login</url-pattern><!--映射路径-->
</servlet-mapping>
<taglib>
<taglib-uri>utilities</taglib-uri>
<taglib-location>/WEB-INF/tlds/utilities.tld</taglib-location>
          <!--自定义标签的实际位置-->
</taglib>


utilities.tld关键部分

<taglib>
<tag>
<name>requestParameter</name>
<tagclass>tags.GetRequestParameterTag</tagclass>
<!--类的位置,如果有包写上-->
<info>Simplest example: inserts one line of output</info>
<bodycontent>Empty</bodycontent>
<attribute>
<name>property</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>


自定义标签类GetRequestParameterTag.java


package tags;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class GetRequestParameterTag extends TagSupport {
private String property;

public void setProperty(String property) {
this.property = property;
}
public int doStartTag() throws JspException {
ServletRequest reg = pageContext.getRequest();
String value = reg.getParameter(property);

try{
pageContext.getOut().print(value == null ? "":value);
}catch(java.io.IOException e){
throw new JspException(e.getMessage());
}
return SKIP_BODY;
}
}
 
登陆成功welcome.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Welcome Page</title>
</head>
<body>
<jsp:userBean id="user" scope="session" class="beans.User"/>
<!--也可以
<%
User user = (User)session.getAttribute("user");
%>
-->
欢迎你:<font color=red><%=user.getUserName()%></font>
</body>
</html>


登陆失败loginFailed.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Login Failed</title>
</head>

<body>
<font color="#993366">请输入用户名和密码,或者创建一个新用户!</font>
<%@ include file="/login_form.jsp"%>
<hr>
<a href="<%=response.encodeURL("newAccount.jsp")%>">创建一个新用户 </a>
</body>
</html>

新建用户newAccount.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>New Account</title>
</head>

<body>
<font color="#996633">创建新用户 </font>
<form name="form1" method="post" action="<%=response.encodeURL("new_account")%>">
<table width="75%" border="0" cellpadding="3">
<tr>
<td width="42%" align="right">用户名:</td>
<td width="58%"><input type="text" name="userName"></td>
</tr>
<tr>
<td align="right">密码:</td>
<td><input type="text" name="userPwd"></td>
</tr>
<tr>
<td align="right">密码问题:</td>
<td><input type="text" name="hint"></td>
</tr>
<tr align="center">
<td colspan="2"> <input type="submit" name="Submit" value="提交"> </td>
</tr>
</table>
</form>
</body>
</html>

注册的控制器NewAccountServlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

import beans.LoginDB;

public class NewAccountServlet extends HttpServlet {

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
LoginDB loginDB = (LoginDB)getServletContext().getAttribute("loginDB");
loginDB.addUser(request.getParameter("userName"),
request.getParameter("userPwd"),
request.getParameter("hint"));
request.getRequestDispatcher(response.encodeUrl("accountCreated.jsp")) .forward(request,response);
}
}

accountCreated.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>

<body>
新用户已经创建! <font color="#0000FF"><%=request.getParameter("userName")%></font>
<hr><%@ include file="login_form.jsp"%>
</body>
</html>
原文地址:https://www.cnblogs.com/KUDO/p/436581.html