zoukankan      html  css  js  c++  java
  • java struts2入门学习实例--将客户端IP地址和访问方式输出到浏览器

     

    实例1:实现客户端IP地址和访问方式输出到浏览器。

    IpAction.java

    复制代码
    package com.amos.web.action;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    /**
     * @ClassName: IpAction
     * @Description: TODO
     * @author: amosli
     * @email:amosli@infomorrow.com
     * @date Jan 5, 2014 4:22:06 PM
     */
    public class IpAction extends ActionSupport {
        private static final long serialVersionUID = -5488264951167516910L;
    
        public String execute() throws Exception {
            // 获取HttpServletRequest对象和HttpServletResponse对象
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();
            // 获取客户端ip地址
            String clientIP = request.getRemoteAddr();
            // 取得客户端的访问方式
            String method = request.getMethod();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("客户端访问的IP为:" + clientIP + "<br>");
            response.getWriter().write("客户端的访问方式为:" + method);
            return null;
        }
    }
    复制代码

    ip_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="ip" namespace="/" extends="struts-default">
            <action name="IpAction" class="com.amos.web.action.IpAction"
                method="execute"></action>
        </package>
    </struts>
    复制代码

    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>
        <!-- 加载其他配置文件 -->
        <include file="config/ip_struts.xml"></include>
    </struts>
    复制代码

    配置完成,部署运行,查看输出。

    输出结果截图: 

    代码分析:

    IpAction.java

    struts2提供了使用ServletActionContext封装了常用的request和response对象,这里

    >>1、使用ServletActionContext.getRequest()获取request对象,

    >>2、ServletActionContext.getResponse()获得response对象。

    >>3、使用request.getRemoteAddr()方法获取访问端的ip地址;

    >>4、request.getMethod()方法获取客户端访问的方式;

    ip_struts.xml 

    包名必须唯一,namespace可以省略,result属性这里没有用到,因为IpAction中return null,如果retrun "string" ,则必须配置result;

    struts.xml

    这里不需要配置其他的,只需要引入ip_struts.xml文件即可,使用include引入,引入的地址为相对路径,是否引入成功,查看tomcat启动时的提示信息,或者ctrl点击路径看能不能访问。

    实例2:将实例1中的信息通过jsp输出

     方法一:

     IpAction.java

    复制代码
    package com.amos.web.action;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    /**
     * @ClassName: IpAction
     * @Description: TODO
     * @author: amosli
     * @email:amosli@infomorrow.com
     * @date Jan 5, 2014 4:22:06 PM
     */
    public class IpAction extends ActionSupport {
        private static final long serialVersionUID = -5488264951167516910L;
        public String execute() throws Exception {
            // 获取HttpServletRequest对象和HttpServletResponse对象
            HttpServletRequest request = ServletActionContext.getRequest();
    //        HttpServletResponse response = ServletActionContext.getResponse();
            // 获取客户端ip地址
            String clientIP = request.getRemoteAddr();
            // 取得客户端的访问方式
            String method = request.getMethod();
            // response.setContentType("text/html;charset=utf-8");
            // response.getWriter().write("客户端访问的IP为:" + clientIP + "<br>");
            // response.getWriter().write("客户端的访问方式为:" + method);
            request.setAttribute("clientIP", clientIP);
            request.setAttribute("method", method);
            System.out.println("method:"+method);
            return "toJSP";
        }
    }
    复制代码

    ip_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="ip" namespace="/" extends="struts-default">
            <action name="IpAction" class="com.amos.web.action.IpAction"
                method="execute">
                <result name="toJSP" type="dispatcher">
                    /ip.jsp
                </result>
            </action>
        </package>
    </struts>
    复制代码

    ip.jsp是放在webapp目录下的

    复制代码
    <%@page import="java.util.Date"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <%
        String method=request.getAttribute("method").toString();
        String clientIP=request.getAttribute("clientIP").toString();
        %>
        客户端IP是:<%=clientIP %><br/>
        客户端的访问方式为:<%=method %><br><hr>
        客户端访问的IP为:${requestScope.clientIP }<br>
        客户端的访问方式为:${requestScope.method}<br>
    </body>
    </html>
    复制代码

    输出结果截图: 

    代码分析:

      IpAction.java中使用request对象的setAttribute方法传值到request域中。如下所示:

    request.setAttribute("clientIP", clientIP);
    request.setAttribute("method", method);

    并且return “toJSP”,不再局限于"success",其实只要ip_struts.xml中result中name属性值与其对应也就ok了。

    ip_struts.xml 中使用转发默认方式(转发),name的属性值为"toJSP"与  IpAction.java中execute方法返回值相对应。然后将值转发到ip.jsp里

     <result name="toJSP" type="dispatcher">
                    /ip.jsp
                </result>

    ip.jsp中采用了两种取值方式,第一种是基础的传值方式,传值是成功的,另外一种是简写的,一种都没成功,这里先帖出来,以后再慢慢研究吧。

    TODO:servlet和jsp 的传值问题。

    使用request对象的getAttribute方法来取值,然后再使用jsp的基本输出方式将值输出。

    servlet有三个域对象:HttpServletRequest、ServletContext、HttpSession

    方法二:

    使用ServletContext如何进行传值呢?如下所示,IpAction类中的execute方法改写为:

    复制代码
          // 获取HttpServletRequest对象和HttpServletResponse对象
            HttpServletRequest request = ServletActionContext.getRequest();
            // 获取servletcontext域
            ServletContext servletContext = ServletActionContext.getServletContext();
          // 获取客户端ip地址
            String clientIP = request.getRemoteAddr();
            // 取得客户端的访问方式
            String method = request.getMethod();
    
            // 将信息绑定到servletContext中
            servletContext.setAttribute("clientIP", clientIP);
             servletContext.setAttribute("method", method);
            
            return "toJSP";
    复制代码

    ip.jsp改写为:

    复制代码
        <%
        String method=application.getAttribute("method").toString();
        String clientIP=application.getAttribute("clientIP").toString();
        %>
        客户端IP是:<%=clientIP %><br/>
        客户端的访问方式为:<%=method %><br><hr>
        [客户端访问的IP为]:${applicationScope.clientIP }<br>
        [客户端的访问方式为]:${applicationScope.method}<br>
    复制代码

     

    输出结果为:

     

     方法三(重点):

    Ip_Action.java 中execute方法需要改的地方:

            //获取HttpSession域 
            Map<String, Object> session = ActionContext.getContext().getSession();
            //将信息绑定到servletSession中
            session.put("clientIP", clientIP);
            session.put("method", method);

    ip.jsp中需要改动的地方:

    复制代码
            <%
        String method=session.getAttribute("method").toString();
        String clientIP=session.getAttribute("clientIP").toString();
        %>
        客户端IP是:<%=clientIP %><br/>
        客户端的访问方式为:<%=method %><br><hr>
        [[客户端访问的IP为]]:${sessionScope.clientIP }<br>
        [[客户端的访问方式为]]:${sessionScope.method}<br>
    复制代码

    这里使用ActionContext获取session对象,再用getAttribute方法获取传过来的值。

    输出结果为:

     为什么ActionContext.getContext().getSession()会是Map集合?

    struts2中有很多个默认拦截器(interceptor),在struts2源码中struts-default.xml中可以查看具体有哪些拦截器。interceptor-stack中有18个拦截器。

     其中有一个拦截器将map中的值转为session值,例如,String method=map.get("method");HttpSession.setAttribute("method",method)

    自动将map中的值转为session,这样做的目的是尽量少出现或者不出现ServletAPI,以达到解耦的作用。

  • 相关阅读:
    Sum Root to Leaf Numbers
    Sum Root to Leaf Numbers
    Sort Colors
    Partition List
    Binary Tree Inorder Traversal
    Binary Tree Postorder Traversal
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Search a 2D Matrix
    leetcode221
  • 原文地址:https://www.cnblogs.com/Jeely/p/11438068.html
Copyright © 2011-2022 走看看