您的位置:首页 > 编程语言 > Java开发

20170918_chr_newlogin Struts2实现登陆功能(简单validate验证)

2017-12-13 13:23 721 查看

Struts2实现登陆功能

/20170918_chr_newlogin/src/nuc/sw/action/LoginAction.java

package nuc.sw.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
private String username;
private String password;
private String type;

public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
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(username.equals("程浩然")&&password.equals("123")) {
ActionContext.getContext().getSession().put("user",username);
ActionContext.getContext().getSession().put("type",type);
return SUCCESS;
}
else {
ActionContext.getContext().getSession().put("error","用户名或密码错误");
return ERROR;
}
}
public void validate() {
if(username==null||username.trim().equals("")) {
this.addFieldError("usernameError", "用户名不能为空");
}
if(password==null||password.trim().equals("")) {
this.addFieldError("passwordError", "密码不能为空");
}
}

}


/20170918_chr_newlogin/src/struts.xml

<struts>
<!-- Add packages here -->
<package name="user" namespace="/" extends="struts-default">
<action name="LoginAction" class="nuc.sw.action.LoginAction">
<result name="success">
/welcome.jsp
</result>
<result name="error">
/login.jsp
</result>
<result name="input">
/login.jsp
</result>
</action>
</package>
</struts>


/20170918_chr_newlogin/WebContent/login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>登录页</title>
</head>
<body>
<font color="red">${sessionScope.error}</font>
<font color="red"><s:fielderror></s:fielderror></font>
<form action="LoginAction" method="post">
用户名:<input type="text" name="username"><br>
密    码:<input type="text" name="password"><br>
用户类型:<select name="type">
<option>普通用户</option>
<option>管理员</option>
</select><br>
<input type="submit" value="登陆">
</form>
</body>
</html>


/20170918_chr_newlogin/WebContent/welcome.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>欢迎页</title>
</head>
<body>
欢迎${session.type}${session.user}登陆!
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2.0