使用者登入幾乎是每一個Web系統的必需模組,本期教程就通過使用者登入模組來講解Struts2.1.6的Action和Result的Annotation配置。
上期的Struts 2.1.6 精簡執行個體系列教程(1):環境的搭建與HelloSimple中,我們建的package名為“cn.simple.action”,這些包名有一個規則的,只要包含 “action,actions,struts,struts2”都會預設被掃描到為Action類,也就是說,我們只要配置了如 “cn.simple.action”、“cn.simple.struts”、“cn.simple.action.admin”等包名,就可以不用在設定檔struts.xml(Struts2.0的設定檔)中配置這些Action類了。當然,這些包名,也可以是別的,但要寫一點點配置,我們就用預設的吧。關於這方面的詳細說明,還是強烈建議大家先看官方的文檔http://struts.apache.org/2.1.6/docs/convention-plugin.html。
好,我們開始寫我們的使用者登入模組吧。先寫個loginform.jsp,記得,不要忘記我們把JSP檔案放在Web-Inf/content/目錄下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登入頁</title>
</head>
<body>
<s:fielderror></s:fielderror>
<form action="login.action" method="post">
帳號<input type="text" name="loginName" value="${loginName}"/><br/>
密碼<input type="password" name="password"><br/>
<input type="submit" value="登入"/>
</form>
</body>
</html>
大家如果想用Struts 2的標籤庫的話,也可以用Struts 2的Form標籤,用之前,要在JSP頭配置上Struts 2標籤庫,換成Struts 2標籤的版本後,即:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:fielderror></s:fielderror>
<s:form action="login">
<s:textfield name="loginName"></s:textfield>
<s:password name="password"></s:password>
<s:submit value="登入"></s:submit>
</s:form>
</body>
</html>