Struts2使用Web组件

用接口访问ServletAPI

为了在Action中直接访问ServletAPI,Struts2还提供了一系列接口。

ServletRequestAware:可以直接访问HttpServletRequest实例

ServletResponseAware:可以直接访问HttpServletResponse实例

SessionAware:可以直接访问Web应用的HttpServletResponse实例

ServletContextAware:可以直接访问ServletContext实例


Action.java

package com.wan;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

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


public class Action extends ActionSupport implements ServletRequestAware{

	private static final long serialVersionUID = -2295563990921774523L;
	private String username;
	private String password;
	private HttpServletRequest req;

	@Override
	public String execute() throws Exception {

		if("wh".equals(username)&&"123".equals(password))
		{
			req.setAttribute("username", username);
			req.setAttribute("password", password);
			return SUCCESS;
		}else
		{
			req.setAttribute("error", "登录失败");
			return ERROR;
		}

	}

	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 void setServletRequest(HttpServletRequest arg0) {
		req=arg0;
	}

	
}
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="default" namespace="/" extends="struts-default">
        <action name="login" class="com.wan.Action">
                <result name="success">/success.jsp</result>
                <result name="error">/fail.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>FirstFilter</filter-name>
	   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>FirstFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
   <form action="login" method="post">
  		  name:<input type="text" name="username"><br/>
  	 	  password:<input type="password" name="password"><br/>
	 	  <input type="submit" name="登录">  
   </form>
  </body>
</html>
success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  
    登陆成功${requestScope.username } ${password }    
  </body>
</html>
fail.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'fail.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
         登录失败!
  </body>
</html>


通过ActionContext类访问ServletAPI

		ActionContext context=ActionContext.getContext();
		if("wh".equals(username)&&"123".equals(password))
		{
			context.put("username", username);
			context.put("password", password);
			return SUCCESS;
		}else
		{
			context.getApplication().put("error", "登录失败");
			return ERROR;
		}

Struts2提供了ActionContext类,通过ActionContext类访问Servlet API。

下面是ActionContext类中包含的几个常用方法。

1、public Object get(Object key):取得HttpServletRequest中key的值;

2、void put(String key,Object value):设置HttpServletRequest中key的值为value;

3、public Map getApplication():获取封装了ServletContext的Map对象;

4、void setApplication(Map application):设置ServletContext实例;

5、static ActionContext getContext():静态方法,获取系统的ActionContext实例;

6、Map getParameters():类似于HttpServletRequest中的getParametersMap方法;

7、public Map getSession():获取封装了HttpSession的Map对象;

8、void setSession(Map session):直接传入一个Map实例,将该Map实例里的key-value对转换为session的属性名和属性值;

相关文章
相关标签/搜索