Struts2 ActionContext(二十四)

迎著太陽走向遠方發表於2017-03-27
1.在web中需要訪問的Servlet API 是HttpServletRequest,HttpServletSession,ServletContext 這3個類代表了JSP的內建物件的request session application

下面是間接訪問Srevlet API(後一章會直接訪問Servlet API)
2.ActionContext類
建立例項化物件 是
ActionContext ac=ActionContext.getContext();
在ActionContext中有一些常用的方法:
Map getApplication();
Map getParameters();
Map getSession()
void setAppliaction(Map application)

3.action.java

package com.sh.action;

import java.util.Map;

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

public class LoginAction extends ActionSupport{
	private String loginName;
	private String loginPassword;

	public String checkLogin(){
		ActionContext ac=ActionContext.getContext();
		Map app=ac.getApplication();
		ac.getSession().put("login", this.loginName);
		ac.getApplication().put("login",this.loginName);
		return SUCCESS;
	}


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" extends="struts-default">
    	<action name="loginAction" class="com.sh.action.LoginAction" method="checkLogin">
    		<result>/index.jsp</result>
    	</action>
    </package>
</struts>



login.jsp

 <body>
    <center>
    	<s:form action="loginAction" method="post">
    		<s:textfield name="loginName" label="loginName" />
    		<s:textfield name="loginPassword" label="loginPassword"/>    	
    		<s:submit key="loginBtn"/>
    		<s:token/>
    	</s:form>
    
    </center>
  </body>

index.jsp

  <body>
   讀取session中的資訊 <s:property value="#session.login"/>
 讀取application中的資訊<s:property value="#application.login"/>
  </body>

相關文章