如果使用struts2,就需要配置文件或者注解,关于struts2的配置文件struts.xml非常熟悉,对于注解可能spring使用的比较多。配置文件的繁琐衬托出了注解的简洁方便,一条或者几条注解解决配置文件几行的内容。
struts2作为控制器建立模型与视图数据的交互。主要对action进行配置。
首先下载struts2-convention-plugin这个jar包,这是使用注解的支持jar包,建议下载最新的版本,可以到struts2的官网上下载最新的全部依赖文件的压缩包
选择需要的依赖文件,注意最新版本的struts2依赖的asm这个jar包也是有要求的,报错了很久在stackoverflow上找到了可靠的解决办法
struts2使用注解还是要使用配置文件配置几条……,在src下新建struts.xml,写入下面的配置
新建login.jsp:
<%-- Created by IntelliJ IDEA. author: DuzhenTong Date: 2018/1/23 Time: 22:35--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>success.jsp:登录
<%-- Created by IntelliJ IDEA. author: DuzhenTong Date: 2018/1/23 Time: 22:40--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>error.jsp:欢迎 登录成功!!!
<%-- Created by IntelliJ IDEA. author: DuzhenTong Date: 2018/1/23 Time: 22:42--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>web.xml配置如下:失败 用户名或密码错误!!!
login.jsp struts2 org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter struts2 /*
在src下新建domain包,新建User类
package domain;/** * Created with IDEA * * @author DuzhenTong * @Date 2018/1/23 * @Time 22:29 */public class User { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; }}
新建action包,新建LoginAction类(使用注解的action所在的包名必须是action,actions等等,在官方的文档中有说明,可以参考):
package action;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.convention.annotation.*;/** * Created with IDEA * * @author DuzhenTong * @Date 2018/1/23 * @Time 22:30 */@ParentPackage("struts-default")@Namespace("/user")public class LoginAction extends ActionSupport { private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Action(value="login", results={ @Result(name="success", location="/success.jsp"), @Result(name="error", location="/error.jsp")}) public String login(){ if ("a".equals(name) && "a".equals(password)) { System.out.println("成功"); return "success"; } return "error"; }}上面的注解和配置文件中的配置很像,配置表单的action,返回什么样的字符串跳转到什么页面
整体的结构:
发布项目启动服务器发起访问输入用户名和密码测试