Struts2的核心功能是action,对于开发人员来说,使用Struts2主要就是编写action,action类通常都要实现com.opensymphony.xwork2.Action接口,并实现该接口中的execute()方法。
在实际开发中,action类很少直接实现Action接口,通常都是从com.opensymphony.xwork2.ActionSupport类继承,ActionSupport实现Action接口和其他一些可选的接口,提供了输入验证,错误信息存取,以及国际化的支持,选择从ActionSupport继承,可以简化action的定义。
开发好action之后,需要对action进行配置,以告诉Struts2框架,针对某个URL的请求应该交由哪个action进行处理
下面举个例子:
**下面这个StudentAction中的方法与struts配置文件中的相对应**
//获取学生
public String getStudent(){
if(stu!=null){
Student student= sd.getStudent(stu.getId());
request.put("student", student);
return SUCCESS;
}
return ERROR;
}
//添加学生
public String addStudent(){
if(stu!=null){
sd.addStudent(stu);
return "show";
}
return ERROR;
}
//删除学生
public String deleteStudent(){
if(stu!=null){
sd.deleteStudent(stu.getId());
return "show";
}
return ERROR;
}
//更新学生
public String updateStudent(){
if(stu!=null){
Student student = sd.getStudent(stu.getId());
student.setAge(stu.getAge());
student.setName(stu.getName());
sd.updateStudent(student);
return "show";
}
return ERROR;
}
//获取学生集合
public String showStudent(){
List<Student> list =sd.showAllStudent();
request.put("students", list);
return SUCCESS;
}
struts配置通用action
<struts>
<!-- 开启struts2的开发模式 -->
<constant name="struts.devMode" value="true" />
<package name="student" extends="struts-default" namespace="/">
<action name="student_*" class="com.my.action.StudentAction" method="{1}">
<result>/student_{1}.jsp</result>
<result name="show" type="redirectAction">student_showStudent</result>
<result name="error">/faild.jsp</result>
<allowed-methods>getStudent,addStudent,deleteStudent,updateStudent,showStudent</allowed-methods>
</action>
</package>
</struts>