码迷,mamicode.com
首页 > 其他好文 > 详细

Struts学习(二)

时间:2018-08-29 20:31:14      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:att   2.3   doc   his   attr   font   在线人数   cookie   效果   

1.复习搭建Struts2的开发环境:3个步骤

 

2.action VS Action类


1).action:代表一个Struts2的请求。
2).Action类:能够处理Struts2请求的类


  >属性的名字必须遵守与 JavaBeans 属性名相同的命名规则.

  >属性的类型可以是任意类型.

    从字符串到非字符串(基本数据库类型)之间的数据转换可以自动发生 必须有一个不带参的构造器
  >至少有一个供 struts 在执行这个 action 时调用的方法 同一个 Action 类可以包含多个 action 方
法.


Struts2 会为每一个 HTTP 请求创建一个新的 Action 实例 ,即Action不是单例的,是线程安全的。


 


2.在Action中访问WEB资源:


1).什么是WEB资源?

HttpServletRequest,HttpSess,ServletContext等的Servlet API


2).为什么访问WEB资源?
B\S的应用的Controller中必须访问WEB资源:向域对象中读写属性,读写Cookie,获取realpath等


3).如何访问?
1.和Servlet API解耦的方式:只能访问有限的Servlet API对象,且只能访问有限的的方法(读取请求参
数,读写域对象的属性,使session失效等)
>使用ActionContext
>实现xxxAware接口
>选用的建议:若一个Action类中有多个action方法,且多个方法都需要使用域对象的Map或
parameter,则建议使用Aware接口的方式
>session对应的Map实际上是SessionMap类


2.和Servlet API耦合的方式:可以访问更多的Servlet API对象,且可以调用其原生的方法。

>使用ServletActionContext
>实现ServletxxxAware接口。

 TestAwareAction.java

package com.yuyi.struts2.action;

import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

public class TestAwareAction implements ApplicationAware,SessionAware,RequestAware,ParameterAware{
    
   public String execute()  {
    
       //1.向application中加入一个属性:application2-applicationValue2
       application.put("applicationKey2", "applicationValue2");
       //2.从application中读取一个属性date,并打印 
       
       return "success";
       
   }
  private Map<String, Object> application;
@Override
public void setApplication(Map<String, Object> application) {
    this.application=application;
    
}
@Override
public void setParameters(Map<String, String[]> arg0) {
    // TODO Auto-generated method stub
    
}
@Override
public void setRequest(Map<String, Object> arg0) {
    // TODO Auto-generated method stub
    
}
@Override
public void setSession(Map<String, Object> arg0) {
    // TODO Auto-generated method stub
    
}
}

 

TestActionContextAction.java

package com.yuyi.struts2.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;

public class TestActionContextAction {
    public String execute() {
        //0.获取ActionContext对象
        //ActionContext是Action的上下文对象,可以获取当前Action的一切信息
        ActionContext actionContext=ActionContext.getContext();
        //1.获取application对应的Map,并向其中添加一个属性
        //通过调用ActionContext对象的getApplication()方法来获取application对应的Map对象
        Map<String, Object> applicationMap=actionContext.getApplication();
        //设置属性
        applicationMap.put("applicationKey", "applicationValue");
        //获取属性
        Object date=applicationMap.get("date");
        System.out.println("date"+date);

        //2.session
        Map<String, Object> sessionMap=actionContext.getSession();
        sessionMap.put("sessionKey", "sessionValue");

        //3.request
        //ActionContext中并没有提供getRequest方法来获取request对应的Map
        //需要手工调用get()方法,传入request字符串来获取
        Map<String, Object> requestMap=(Map<String, Object>) actionContext.get("request");
        requestMap.put("requestKey", "requestValue");
        //4.获取请求参数对应的Map,并获取指定的参数值
        //键:请求参数的名字,值:请求参数的值对应的字符串数组
        //注意:1.getParameters的返回值在Map<String,Object>,而不是Map<String,String[]>
           // 2.pamaters这个Map只能读不能写入数据,一旦想写入,不出错,但没有效果
        Map<String, Object> parameters=actionContext.getParameters();
        System.out.println(((String[])parameters.get("name"))[0]);
        
        parameters.put("age", 100);
        return "success";
    }
}

 

 TestServletActionContextAction.java

package com.yuyi.struts2.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class TestServletActionContextAction {

    public String execute() {
/**
 * ServletActionContext:可以从中获取到当前Action对象需要的一切Servlet API相关的对象。
 * 常用的方法:
 * 1.获取HttpServletRequest request=ServletActionContext.getRequest();
 * 2.获取HttpSession session=ServletActionContext.getRequest().getSession();
 * 3.获取ServletContext servletContext=ServletActionContext.getServletContext();
 */
        HttpServletRequest request=ServletActionContext.getRequest();
        HttpSession session=ServletActionContext.getRequest().getSession();
        ServletContext servletContext=ServletActionContext.getServletContext();
        
        System.out.println("execute.....");
        return "success";
    }
}

 

TestServletAwareAction.java
package com.yuyi.struts2.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

public class TestServletAwareAction implements ServletRequestAware,ServletContextAware,ServletResponseAware{
/**
 * 通过实现ServletxxxAwawre接口的方式可以由Struts注入
 * 需要的Servlet相关的对象
 * 
 * ServletRequestAware:注入HttpServletRequest对象
 * ServletContextAware:注入ServletContext对象(较为常用)
 * ServletResponseAware:注入HttpServletResponse对象
 */
    @Override
    public void setServletResponse(HttpServletResponse response) {
        System.out.println(response);
        
    }
  private ServletContext context;
    @Override
    public void setServletContext(ServletContext context) {
        System.out.println(context);
        this.context=context;
        
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        System.out.println(request);
    }
public String execute() {
    System.out.println("ServletContext"+context);
    return "success";
    
}
}

 

Struts.xml

 

<package name="default"  extends="struts-default">
    <action name="TestActionContext"
    class="com.yuyi.struts2.action.TestActionContextAction"
    >
    <result>/test-actionContext.jsp</result>
    </action>
    
    <action name="TestAware"
    class="com.yuyi.struts2.action.TestAwareAction"
    >
    <result>/test-aware.jsp</result>
    </action>
    
    <action name="TestServletActionContext" 
    class="com.yuyi.struts2.action.TestServletActionContextAction">
    <result>/success.jsp</result>
    </action>
    
    <action name="TestServletAware" class="com.yuyi.struts2.action.TestServletAwareAction">
    <result>/success.jsp</result>
    </action>
    </package>
</struts>

 

 

 

index.jsp

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="TestActionContext.do?name=yuyi">Test ActionContext</a>
    <br>
    <br>
    <a href="TestAware.action?name=yuyi">Test Aware</a>
    <br>
    <br>
    <a href="TestServletActionContext.action">Test ServletActionContext</a>
    <br>
    <br>
    <a href="TestServletAware.action">Test ServletAware</a>
    <br>
    <br>
 

    <%
        if (application.getAttribute("date") == null)
            application.setAttribute("date", new Date());
    %>
</body>
</html>

 

test-actionContext.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
        <h4>Test ActionContext Page</h4>
        
        applicationKey:${applicationScope.applicationKey}
        <br><br>
        
        session:${sessionScope.sessionKey}
        <br><br>
        request:${requestScope.requestKey}
        <br><br>
        age:${parameters.age}
</body>
</html>

 

test-aware.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  
  <h4>Test Aware Page</h4>
  
  application:${applicationScope.applicationKey2}
</body>
</html>

 



3.请求的扩展名问题


1).org.apache.struts2报下的default.properties中配置了Struts应用的一些常量
2).struts.action.extension定义了当前Struts2可以接受的请求的扩展名。
3).可以在struts.xml中以常量配置的方式修改default.properties所配置的常量

<constant name="struts.action.extension" value="action,do"></constant>

 

 


 

4.ActionSupport

1).ActionSuuuort是默认的Action类:若某个action节点没有class属性,即ActionSupport为待执行的
Action类,而execute方法即为要默认执行的action方法

<action name="testActionSupport" class="com.opensymphony.xwork2.ActionSupport" 
method="execute">
<result>/testActionSupport.jsp</result>
</action>

 

2).在手工完成字段验证,显示错误消息,国际化等情况下,推荐继承ActionSupport,

index.jsp

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="testActionSupport.do">Test ActionSupport</a>

</body>
</html>

 

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>

<!-- 配置Struts可以受理的请求的扩展名 -->
<constant name="struts.action.extension" value="action,do"></constant>

  <package name="default"  extends="struts-default">

<action name="testActionSupport">
<result>/testActionSupport.jsp</result>
</action>

</package>

</struts>

 testActionSupport.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

     <h4>Test ActionSupport Page</h4>

</body>
</html>

 

一个练习,实现在线人数统计和在线人数减一和加一

index.jsp

%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="login-ui.do">LoginUI</a>
</body>


</html>

 

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>

<!-- 配置Struts可以受理的请求的扩展名 -->
<constant name="struts.action.extension" value="action,do"></constant>

  <package name="default"  extends="struts-default">

<action name="login-ui">
<result>/login.jsp</result>
</action>

<action name="user-login" class="com.yuyi.struts2.action.UserAction">
<result name="login-success">/login-success.jsp</result>
</action>

<action name="logout" class="com.yuyi.struts2.action.UserAction" method="Logout">
<result name="logout-success">/login.jsp</result>
</action>

</package>

</struts>

 

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

      <form method="post" action="user-login.do">
      username:<input type="text" name="username"/>
      <input type="submit" value="Login">
      </form>
</body>
</html>

 

login-success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   
   Welcome:${sessionScope.username }
   <br><br>
   
   Count on Line:${applicationScope.count }
   <br><br>
      
   <a href="logout.do">Logout</a>
   
</body>
</html>

 

UserAction.jsp

package com.yuyi.struts2.action;

import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.SessionAware;

public class UserAction implements SessionAware,ApplicationAware{
    
    private String username;
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String Logout() {
        
        //1.在线人数-1:获取在线人数,若数量>0,减一
        Integer count=(Integer) application.get("count");
        if(count !=null && count >0) {
            count--;
            application.put("count", count);
        }
        //2.session失效:强转为SeeionMap,调用invalidate方法
        ((SessionMap)session).invalidate();
        return "logout-success";
    }
    public String execute() {
        
        //把用户信息存入session中
        //1.获取session.通过实现RequestAware接口
        //2.获取登录信息:通过在Action中添加Setter方法
        //3.把用户信息存入Session中
        session.put("username", username);
        //在线人数加一
        //1.获取当前的在线人数,从application中获取
        Integer count=(Integer) application.get("count");
        if(count == null ) {
            count=0;
        }
        //2.使当前人数加一
        count++;
        application.put("count", count);
        return "login-success";
        
    }
private Map<String, Object> session;
    @Override
    public void setSession(Map<String, Object> session) {
        this.session=session;
        
    }
    
    private Map<String, Object> application;
    @Override
    public void setApplication(Map<String, Object> application) {
        this.application=application;
        
    }
}

 

Struts学习(二)

标签:att   2.3   doc   his   attr   font   在线人数   cookie   效果   

原文地址:https://www.cnblogs.com/yuyiWang/p/9556579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!