struts2中的注解

struts2中注解很简单,因为struts.xml中内容本来就不多。下面看看具体怎么配。

配置步骤:先导入一个叫 struts2-convention-plugin-2.3.24.jar 的jar包,然后在我们的动作类中直接去做注解配置就行了。值的注意的是用注解的方式的话,struts.xml文件是不能要的,否则注解配置的那些动作会因为去struts.xml中找不到而报错。

看页面:

<body>
<a href="${pageContext.request.contextPath}/myannotation/justTest">注解方式配置</a>
</body>

看动作类:

package com.dimples.action;

import org.apache.struts2.convention.annotation.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;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("struts-default")	//指定其父包
@Namespace("/myannotation")		//指定其namespace
@Results({    //在类上面指定则是指定公共的results,如果需要单独配置,配置在相应方法上面即可。
	@Result(name="success",type="redirect",location="/index.jsp"),
	@Result(name="error",location="/error.jsp")
})
public class MyAnnotation extends ActionSupport {
	
	@Action(value="justTest")    //配置action的名称
	public String test() {
		return SUCCESS;
	}
}

最后说点细节问题,我们使用注解了却没有在任何地方告诉struts2去哪找我们的注解,它是怎么找到的呢?其实使用注解后struts2默认会去这几层目录下找:action、actions、struts、struts2。只要你的包名中的某一层含这些名字,它都可以找到,比如我写动作类的包名叫com.dimples.action或com.dimples.struts,这样它都能自动找到,否则找不到。当然这个也是可以配置的,在过滤器的初始化参数中做相关配置:

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/81176239