2013年4月3日 星期三

Struts2 - Chapter 2 Start Struts2

使用的版本為Struts2-2.3.8,可到Struts2官網下載
 
配置的目錄及lib如下:














 
 
 

Struts2的配置文件struts.xml基本上置於classes下
 
以下為一個簡單的配置:
 
struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

 <constant name="struts.devMode" value="true" />
 
 <package name="default" namespace="/" extends="struts-default">

  <default-action-ref name="index" />

  <global-results>
   <result name="error">/error.jsp</result>
  </global-results>

  <global-exception-mappings>
   <exception-mapping exception="java.lang.Exception"
    result="error" />
  </global-exception-mappings>

  <action name="loginAction" class="user.action.UserLoginAction" method="login">
   <result name="success">/success.jsp</result>
   <result name="input">/index.jsp</result>
  </action>

 </package>

</struts>

從上到下依序介紹,

struts.devMode 讓你debug時可以隨時重新deploy

struts-default  是一個struts2已經設定好的攔截器及流程,通常都是繼承

default-action-ref 預設的action名稱

global-results 所有的result傳回error時,都會進入/error.jsp

global-exception-mappings 同上,所有出現的Exception都會轉到這

action name 頁面呼叫的名稱

action class 該Action的位置

result name 執行完回傳的字串,並跳轉入該頁面

下面用一個簡單的登入範例顯示:

index.jsp

<html>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
 <s:form name="login" action="loginAction" >
  <s:textfield name="account" label="account" />
  <s:password name="password" label="password" />
  <tr>
   <td>&nbsp;</td>
   <td><s:submit value="login" theme="simple" />
    <s:reset value="reset" theme="simple" /></td>
  </tr>
 </s:form>
</body>
</html>

success.jsp

<html>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
 <s:form >
  <tr>
   <th>account</th>
   <th>password</th>
  </tr>
  <tr>
   <td><s:property value="account" /></td>
   <td><s:property value="password" /></td>
  </tr>
 </s:form>
</body>
</html>

UserLoginAction.java

package user.action;

import com.opensymphony.xwork2.ActionSupport;

public class UserLoginAction extends ActionSupport{
 private String account;
 private String password;
 
 public String getAccount() {
  return account;
 }

 public void setAccount(String account) {
  this.account = account;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String login(){
  return "success";
 }
}


 

1 則留言: