SessionAware接口
通过实现SessionAware接口可以用接口注入的方式向Action中传入一个Map容量,这容器与用户会话有相同的生命周期可以用它来实现用户会话的跟踪(绑定数据到会话)
注解配置Action
导入jar包
struts2-convention-plugin-2.5.10.jar
asm-5.1.jar
例子
可以在类或方法上打注解
@Action(value="login", results={
@Result(name="success", location="/showHouse.do", type="redirect"),
@Result(name="input", location="/login.jsp")
})
验证码
创建CodeAction
public class CodeAction
extends ActionSupport
implements SessionAware{
private static final long serialVersionUID = 1L;
private InputStream imageInputStream;
private Map<String, Object> map;
public InputStream getImageInputStream() {
return imageInputStream;
}
@Override
public void setSession(Map<String, Object> map) {
this.map = map;
}
@Override
public String execute() {
String codeStr = CommonUtil.verifyCodeStr(4);
map.put("code", codeStr);
BufferedImage codeImage = CommonUtil.codeStrToImage(codeStr, 80, 30);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(codeImage, "png", out);
imageInputStream = new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}
}
配置Action
注解
@Action(value="code", results={
@Result(name="success", type="stream", params={
"inputName", "imageInputStream",
"contentType", "image/png"
})
})
xml
<action name="code" class="com.kygo.action.CodeAction">
<result name="success" type="stream">
<param name="inputName">imageInputStream</param>
<param name="contentType">image/png</param>
</result>
检查输入参数合法
4种方法:
1.在jsp页面写js代码
2.继承ActionSupport重写validate()方法 若不是默认的方法,需要自己写一个如validateLogin()
;默认validate+方法名();
3.注解
4.xml
JavaScript
document.forms[0].addEventListener('submit', function(evt) {
evt.preventDefault();
var username = document.getElementById('username').value;
var flag = check(username, /^\w{5,20}$/);
var password = document.getElementById('password').value;
flag = flag && check(password, /^\w{6,20}$/);
var codeStr = document.getElementById('codeStr').value;
flag = flag && check(codeStr, /^[a-zA-Z0-9]{4}$/);
if (flag) {
this.submit();
}
else {
window.alert('请输入有效的登录信息');
}
});
function check(str, regex) {
return str.match(regex);
}
java代码
public void validateLogin() {
String username = user.getUsername();
String password = user.getPassword();
if (username == null || !username.matches("^\\w{5,20}$")) {
addFieldError("uidError", "无效的用户名");
}
if (password == null || !password.matches("^\\w{6,20}$")) {
addFieldError("pwdError", "无效的密码");
}
}
结果会放在fieldErrors里
注解
@Validations(
requiredStrings={
@RequiredStringValidator(
trim=true,
fieldName="username",
message="用户名不能为空"
),
@RequiredStringValidator(
fieldName="password",
message="密码不能为空"
)
},
stringLengthFields={
@StringLengthFieldValidator(
trim=true,
fieldName="username",
minLength="5",
maxLength="20"
)
}
)
xml
放在对应类同一包下,名字必须是遵循UserAction-validation.xml
类名-validation.xml
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>用户名不能为空</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">20</param>
<message>用户名长度在${minLength}~${maxLength}个字符之间</message>
</field-validator>
</field>
</validators>
json
例子:检查用户名是否被注册
jsp-js代码
$('#username').on('blur', function() {
var username = $(this).val();
$.getJSON('check.do',
{"username": username},
function(data) {
data.done ? showCorrectHint() : showErrorHint();
}
);
});
第一种方法:普通
Action
@Action(value="check", results={
@Result(name="success", type="stream", params={
"inputName", "jsonInput",
"contentTyoe", "application/json"
})
})
public String check() {
boolean done = getUserService().checkUnique(user.getUsername());
String jsonStr = "{\"done\": " + done + "}";
jsonInput = new ByteArrayInputStream(jsonStr.getBytes());
return SUCCESS;
}
xml
<result name="success" type="stream">
<param name="inputName">jsonInput</param>
<param name="contentType">application/json</param>
</result>
第二种方法:使用json插件
导入jar包struts2-json-plugin-2.5.10.jar
Action
public class CheckAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private boolean valid;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JSON(name="done")
public boolean isValid() {
return valid;
}
@Override
public String execute() throws Exception {
valid = getUserService().checkUnique(username);
return SUCCESS;
}
private UserService getUserService() {
return ServiceFactory.factory(UserService.class);
}
}
xml
<action name="check" class="com.kygo.action.CheckAction">
<result name="success" type="json"></result>
</action>