一个简单关于struts2的login问题。
JAVA代码:
package cn.cjh.action;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
public class LoginAction implements Action {
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 {
ActionContext ctx = ActionContext.getContext();
Integer counter = (Integer)ctx.getApplication().get("counter");
if(counter == null)
{
counter = 1;
}
else
{
counter += 1;
}
ctx.getApplication().put("counter", counter);
ctx.getSession().put("user", getUsername());
if(getUsername().equals("cjh")&&getPassword().equals("cjh"))
{
ctx.put("tip", "登录成功");
return SUCCESS;
}
else
{
ctx.put("tip", "不成功");
return ERROR;
}
}
}
struts.xml文件位置放在SRC下。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="login" class="cn.cjh.action.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
web.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
login.jsp 代码:
<%@ page contentType="text/html; charset=GBK" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form action="login.action" method="post">
<table align="center">
<caption><h3>用户登录</h3></caption>
<tr>
<td>用户名:<input type="text" name="username"/></td>
</tr>
<tr>
<td>密 码:<input type="text" name="password"/></td>
</tr>
<tr align="center">
<td><input type="submit" value="登录"/><input type="reset" value="重填" /></td>