1、用Annotation注释的方式实现Struts2的配置,首先要在lib目录下引入struts2-convention-plugin-2.3.4.jar包。
如下图所示,
我们发现annotation包下所对应的类与struts.xml文件中所要配置的内容几乎完全一致。
2、我们对LoginAction进行Annotation,免struts.xml配置实例。要求正确输出登录信息,错误返回登录页面。
Struts2使用注解开发需要遵循一些规范:(我的开发包不是以.action结尾的就老出错)
1)Action要必须继承ActionSupport父类;
2)Action所在的包名必须以 .action 结尾;
<1>login.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 action="login.action" method="post">
username:<input type="text" name="username">
password:<input type="text" name="password">
<input type="submit" value="submit">
</form>
</body>
</html>
<2>编写action类
package cn.sict.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("struts-default")
@Action(value = "login", results = {
@Result(name = "success", location = "/result.jsp"),
@Result(name = "input", location = "/login.jsp", type = "redirect") })
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
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;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
if ("aaa".equals(username) && "aaa".equals(password))
return SUCCESS;
else
return INPUT;
}
}
<3>result.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>
username:${requestScope.username}<br>
password:${requestScope.password}<br>
</body>
</html>
参考资料: http://blog.csdn.net/liujiahan629629/article/details/22696589