JSP-一個理解MVC架構的簡單的登陸、註冊例子

來源:互聯網
上載者:User

首先我們看看這個目錄結構


--+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>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.