java struts2入門學習實例--用戶注冊


 一、用戶注冊示例

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    <form name="register" action="/struts2/RegisterAction" method="POST">
        <table border="2" align="center">
            <caption>新用戶注冊</caption>
            <tr>
                <th>用戶名:</th>
                <td><input name="username" id="username" type="text" /></td>
            </tr>
            <tr>
                <th>密碼:</th>
                <td><input name="password" id="password" type="password" /></td>
            </tr>

            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交"
                    width="120ppx" /></td>
            </tr>

        </table>
    </form>
</body>
</html>
View Code

 

RegisterAction.java

package com.amos.web.action;

import com.opensymphony.xwork2.ActionSupport;

/** 
* @ClassName: RegisterAction 
* @Description: TODO
* @author: amosli
* @email:amosli@infomorrow.com
* @date Jan 6, 2014 2:31:32 AM  
*/
public class RegisterAction extends ActionSupport {
    private static final long serialVersionUID = -3830387456224903276L;
    private String username;
    private String password;

    public void setUsername(String username) {
        System.out.println("調用 username方法 ");
        this.username = username;
    }

    public void setPassword(String password) {
        System.out.println("調用 password方法 ");
        this.password = password;
    }

    public String register() throws Exception {
        System.out.println("用戶名:"+username+"  密碼:"+password);
        return null;
    }
}

 

register_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>
    <package name="register" namespace="/" extends="struts-default">
        <action name="RegisterAction" class="com.amos.web.action.RegisterAction"
            method="register">
        </action>
    </package>
</struts>

 

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>
    <!-- 加載其他配置文件 -->
    <!--<include file="config/ip_struts.xml"></include>-->

<include file="config/register_struts.xml"></include> </struts>

 

運行結果如下圖所示:

輸入用戶名:張三,密碼:zs,點擊提交,控制台輸出結果如下:

代碼分析:

程序的入口為register.jsp,其中定義了一個表單,其中定義了一個action為"/struts2/RegisterAction",調用方式為POST方式。/struts2項目訪問路徑,其中RegisterAction是由struts.xml進行加載register_struts.xml中的配置,在register_struts.xml中配置class為com.amos.web.action.RegisterAction,method為register,由此進行反射到RegisterAction.java類。然后調用setter/getter方法,進行數據輸出。

 

二、用戶注冊(通過GET)

將register.jsp中的method由POST改為GET方式,再進行訪問register.jsp,輸入張三,zs ,結果如下所示:

為什么出現亂碼? 在struts2中,post方示默認會進行轉碼為utf-8,但get方式卻要手工轉碼.

這里為了使用用戶名顯示正常,將RegisterAction.java中的setUsername方法更改如下:

public void setUsername(String username) {
        System.out.println("調用 username方法 ");
        try {
            // 將tomcat默認編碼轉碼為utf-8
            username = new String(username.getBytes("ISO8859-1"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        this.username = username;
    }

tomcat默認的編碼是歐洲的ISO8859-1,這里轉換一下編碼,再重新運行后,結果如下:

顯示中文正常了,但是如果將jsp中的調用方式再改為POST時,將會再出現亂碼現象,主要是因為已經是utf-8編碼的文字再轉一次編碼就會轉錯。所以這里要進行判斷一下調用方式,代碼優化如下所示:

    public void setUsername(String username) {
        System.out.println("調用 username方法 ");
        String method = ServletActionContext.getRequest().getMethod();
        if(method.equals("GET")){ try {
            // 將tomcat默認編碼轉碼為utf-8
            username = new String(username.getBytes("ISO8859-1"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
       }else if(method.equals("POST")){
            
        }
        this.username = username;
    }

首先取得客戶端的請求方式,如果是get那么將首先轉碼,如是post方式那將什么也不需要做。

 

 所以在實際開發中建議盡量使用POST提交方式,以避免不必要的麻煩。

三、將用戶密碼以jsp頁面的方式顯示

下面將先看效果,再看代碼:

 

 

RegisterAction.java

package com.amos.web.action;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @ClassName: RegisterAction
 * @Description: TODO
 * @author: amosli
 * @email:amosli@infomorrow.com
 * @date Jan 6, 2014 2:31:32 AM
 */
public class RegisterAction extends ActionSupport {
    private static final long serialVersionUID = -3830387456224903276L;
    private String username;
    private String password;

    public void setUsername(String username) {
        System.out.println("調用 username方法 ");
        String method = ServletActionContext.getRequest().getMethod();
        if(method.equals("GET")){
        try {
            // 將tomcat默認編碼轉碼為utf-8
            username = new String(username.getBytes("ISO8859-1"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        }else if(method.equals("POST")){
            
        }
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        System.out.println("調用 password方法 ");
        this.password = password;
    }

    public String register() throws Exception {
        System.out.println("用戶名:" + username + "  密碼:" + password);
        return "toshow";
    }
}
View Code

register_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>
    <package name="register" namespace="/" extends="struts-default">
        <action name="RegisterAction" class="com.amos.web.action.RegisterAction"
            method="register">
            <result name="toshow" type="dispatcher">/show.jsp</result>
        </action>
    </package>
</struts>

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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:property value="username"/>  密碼:<s:property value="password"/>
</body>
</html>

register.jsp和struts.xml都同上面一樣,沒有變化。

 

代碼分析:
這里需求是將表單中輸入的用戶名和密碼輸出到另一個jsp頁面中,那么這里RegisterAction中必須新增加getter方法,return值也不能為null,因為這里要用到result屬性,這里配置register_struts.xml文件,將文件內容轉發到show.jsp.

這里重點就是show.jsp,這里引入struts-core源碼包里的/META-INF/struts-tags.tld,標簽來進行調用數據,s是struts的簡寫,其中value值要和RegisterAction中的兩個實例變量名保持一致。

 注意,這里只標簽取值僅限於轉發的情況下,如果將register-struts.xml中的dispatcher改為redirect那么將取到空值"",如下圖所:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM