Struts2的自动装配

第一种   零散参数的自动装配

action方法

/**
*
* 零散参数自动装配
*/
public class LoginAction implements Action {
private String username;
private String password;
public String execute() throws Exception {
if (username.equals("admin") && password.equals("admin")){
return SUCCESS;
}else {
return LOGIN;
}
}

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;
}
}

struts.xml的action配置文件
<!--零散参数的自动装配-->
<action name="login" class="cn.sjl.day01.controller.LoginAction">
<result name="success">day01/success.jsp</result>
<result name="login">day01/login.jsp</result>
</action>

jsp页面
<%@taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<s:form name="form1" namespace="/" method="post" action="login">
请输入用户名: <s:textfield name="username"></s:textfield> <br/>
<s:password name="password"></s:password><br/>
<s:submit value="登陆"></s:submit>
</s:form>
</body>
</html>


第二种 JavaBean(对象)类型的自动装配

Action方法
public class UserInfo {
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;
}
}

/**
*
* JavaBean类型的自动装配
*/
public class LoginBeanAction implements Action{
private UserInfo info;
public String execute() throws Exception {
if (info.getUsername().equals("admin")&& info.getPassword().equals("admin")){
return SUCCESS;
}else {
return LOGIN;
}
}

public UserInfo getInfo() {
return info;
}
public void setInfo(UserInfo info) {
this.info = info;
}
}

struts.xml的action配置
<!--JavaBean类型的自动装配-->
<action name="loginbean" class="cn.sjl.day01.controller.LoginBeanAction">
<result name="success">day01/success.jsp</result>
<result name="login">day01/loginbean.jsp</result>
</action>

jsp页面
<%@taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<s:form name="form1" namespace="/" method="post" action="loginbean">
请输入用户名: <s:textfield name="info.username"></s:textfield> <br/>
<s:password name="info.password"></s:password><br/>
<s:submit value="登陆"></s:submit>
</s:form>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>成功 </title>
</head>
<body>
登录成功
</body>
</html>


以上就是struts2自动装配,总体来说struts2自动装配还是挺简单的。
原文地址:https://www.cnblogs.com/sujulin/p/8473026.html