Struts2实现简单登陆功能
/20170913_chr_loginchr/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;
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);
return SUCCESS;
}
else {
ActionContext.getContext().getSession().put("error" ,"用户名或密码错误" );
return ERROR;
}
}
}
/20170913_chr_loginchr/src/struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<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 >
</action >
</package >
</struts >
/20170913_chr_loginchr/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" > ${requestScope.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 >
<input type ="submit" value ="登陆" >
</form >
</body >
</html >
/20170913_chr_loginchr/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.user} 登陆!
</body >
</html >