基本文件结构如下图
login.java
package lingzhi; import javax.servlet.jsp.tagext.TryCatchFinally; import com.opensymphony.xwork2.ActionSupport; public class Login extends ActionSupport { public String execute() throws Exception{ setMessage(getText(MESSAGE)); if(isInvalid(getUsername())) return INPUT; if(isInvalid(getPassword())) return INPUT; return SUCCESS; } private boolean isInvalid(String value){ return (!value.equals("www")); } public static final String MESSAGE = "HelloWorld.message"; private String message; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
login-validation.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="lingzhi" namespace="/lingzhi" extends="struts-default"> <action name="Login" class="lingzhi.Login"> <result name="input">/lingzhi/login.jsp</result> <result>/hello.jsp</result> </action> </package> </struts>
login.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="lingzhi" namespace="/lingzhi" extends="struts-default"> <action name="Login" class="lingzhi.Login"> <result name="input">/lingzhi/login.jsp</result> <result>/hello.jsp</result> </action> </package> </struts>
login.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title><s:text name="login"/></title> </head> <body> <s:form action="Login"> <s:textfield key="username" /> <s:password key="password" /> <s:submit/> </s:form> <ul> <li> <s:url id="url" action="Login"> <s:param name="request_locale">en_US</s:param> </s:url> <s:a href="%{url}" mce_href="%{url}">English</s:a> </li> <li> <s:url id="url" action="Login"> <s:param name="request_locale">zh_CN</s:param> </s:url> <s:a href="%{url}" mce_href="%{url}">中文</s:a> </li> </ul> </body> </html>
hello.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title><s:text name="login"/></title> </head> <body> <s:text name="HelloWorld.message"/> </body> </html>
关于struts2从来没用过,听说挺好用的,今天参考了一下官方的demo自己实践了一下,感觉还可以和webwork没多大的区别,就是ui标签有些不顺手,还不如自己手敲html标签,可能是不习惯。