Struts2注解学习1


这是开博的第一篇,我希望每天把我学到的东西记录下来,成为一个知识库,方便以后的学习和分享
在项目中看到用struts2注解来做,很方便,做了一个用户登录的例子
1、加载所需jar包
commons-fileupload-1.2.1 jar
commons-io-1.4.jar
freemarker-2.3.15.jar
ognl-2.7.3 jar
struts2-core-2.1.8 jar
xwork-core-2.1.6 jar
struts2-json-plugin-2.1.8.1 jar
struts2-convention-plugin-2.1.8.1 jar

2、

package com.action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

@Namespace(value="/checkUser")
@ParentPackage(value="struts-default")
@Results(
		{
		@Result(name="yes",location="/check/yes.jsp"),
		@Result(name="no",location="/check/no.jsp")
		}
	)
public class UserAction{
	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 execute() {
		if("1".equals(userName)&&"2".equals(password)){
			return "yes";
		}
		return "no";
	}
}
action类,
 @Namespace(value="/checkUser") 定义该action类的命名空间为checkUser ,
 @ParentPackage(value="struts-default") 默认继承
@Results(
         {
         @Result(name="yes",location="/check/yes.jsp"),
         @Result(name="no",location="/check/no.jsp")
         }
     )  定义该action返回时,跳转的页面
其中action的名字则是 “user” ,默认去掉action,首字母小写
3、配置web.xml
<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <!--

     <init-param> <param-name>actionPackages</param-name> <param-value>com.action</param-value> </init-param>
      -->
</filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

 

  

4、登录验证的jsp页面,如何访问action
 <form action="checkUser/user" method="post"> 
        用户名:<input name="userName"/></br>
        密码:<input name="password"/></br>
        <input type="submit" value="登录"/>
    </form>

 

初次接触struts2注解,还在学习中
posted @ 2014-04-15 09:23  以梦为码  阅读(237)  评论(0编辑  收藏  举报