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 {
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>
<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>