Action
public class UserAction extends ActionSupport implements SessionAware { /** * */ private static final long serialVersionUID = 1L; private String name; private Map<String, Object> session; public String add() { if (name == "" || !name.equals("tom")) { this.addFieldError("name", "this name is wrong!"); this.addFieldError(name, "this name too long!"); System.out.println("name:" + name); return ERROR; } System.out.println("name" + name); session.put("name", name); return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void setSession(Map<String, Object> session) { // TODO Auto-generated method stub this.session = session; } }
web.xml
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
struts.xml
<struts> <!-- 改变xml不用重启服务,开发模式 --> <constant name="struts.configuration.xml.reload" value="true"/> <!-- DMI动态方法调用需要配置 --> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <package name="user" namespace="/" extends="struts-default"> <!-- 默认Action --> <default-action-ref name="index"></default-action-ref> <action name="index"> <result> /index.jsp </result> </action> <action name="user" class="com.buaa.struts2.userAction.UserAction" > <result >/Hello.jsp</result> <result name="error">/index.jsp</result> </action> </package> </struts>
测试的登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath %>" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%-- <s:fielderror fieldName="name" theme="simple"/> <br> --%> <s:debug></s:debug> <form action="user!add" method="post"> <input type="text" name="name"/><s:property value="errors.name[0]"/> <input type="submit" value="提交submit"/> </form> </body> </html>
获取到session的值
<body> hello struts success!<br /> <s:property value="#session.name"/> </body>
时间: 2024-11-10 00:08:41