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

一天教你入门struts2

时间:2015-06-05 12:25:32      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:struts2   javaweb   ip库   

写在前面

  • 自己也是一个java和java web的菜鸟,之前没有接触过java web方面的开发
  • 想通过一个小项目,来熟悉struts2的开发流程
  • 一个有趣的想法源于教研室项目上的一个功能实现–自动识别运营商,去做不同的处理。项目上采用的是IP地址库的方式,在本地做处理。这里为了简单就采用了淘宝提供的接口服务
  • 已经将该项目作为开源项目放在:IP地址仓库 欢迎大家前来点赞

可以学到什么

  • struts2的基本运行流程
  • HttpClient和org.json库的使用
  • 前端采用了bootstrap和ajax,做到了网页的自适应,后端返回json数据和前端交互

步入正题

  • 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>
<!-- 设置常量实现动态调用 -->  
   <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 
   <!-- 名字必须唯一对应模块 -->  
   <package name="hello"  extends="json-default">     
          <default-action-ref name="index" />
          <action name="index" class="action.IPSearchAction" method="index">  
              <!--为了安全将其放在、WEB-INF/pages 不明白的也可放在webRoot  根目录下-->  
                <result name="success">/WEB-INF/pages/ip.jsp  </result>  
          </action>

          <action name="search" class="action.IPSearchAction" method="search">  
              <!--为了安全将其放在、WEB-INF/pages 不明白的也可放在webRoot  根目录下-->  
                <result name="success" type="json">
                    <param name="root">responseMap</param>
                </result>  
          </action>  
   </package>  

</struts>

  • web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <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>
  <welcome-file-list>
    <welcome-file>/WEB-INF/pages/ip.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • action文件
package action;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


public class IPSearchAction {

     String ip;          

     Map<String, Object> responseMap;   //查询的结果为json数据,struts2自动做序列化的工作

    public Map<String, Object> getResponseMap() {
        return responseMap;
    }

    public void setResponseMap(Map<String, Object> responseMap) {
        this.responseMap = responseMap;
    }   

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        System.out.println("input ip is: "+ip);
        this.ip = ip;
    }    

    public String search(){      
        setOutputValue();
        return "success";          
    }


   public String index(){
      return "success";
   }

   public void setOutputValue() {
       HttpClient httpclient = HttpClients.createDefault();
       System.out.println("the input ip is" + ip);
        URI uri = null;
        try {
            uri = new URIBuilder()
                .setScheme("http")
                .setHost("ip.taobao.com")
                .setPath("/service/getIpInfo.php")
                .setParameter("ip", ip)
                .build();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode == HttpStatus.SC_OK) { //状态==200,返回成功
            String result = null;
            try {
                result = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(result);
            JSONObject resultJson  = new JSONObject(result);
            int code      = resultJson.getInt("code");
            String country = null;
            String region = null;
            String city = null;
            String county = null;
            String isp = null;
            if(code == 0) {
                country = resultJson.getJSONObject("data").getString("country");  
                region = resultJson.getJSONObject("data").getString("region"); 
                city = resultJson.getJSONObject("data").getString("city"); 
                county = resultJson.getJSONObject("data").getString("county"); 
                isp = resultJson.getJSONObject("data").getString("isp"); 
                System.out.println("code is: "+ code + "country is: " + country + "area is "+region+"county is "+county+
                        "isp is "+isp); 
            } 

            responseMap = new HashMap<String, Object>();
            responseMap.clear();
            responseMap.put("country", country);
            responseMap.put("region", region);
            responseMap.put("city", city);
            responseMap.put("county", county);
            responseMap.put("isp", isp);

        }
   }
}
  • 依赖的库文件
    技术分享
    说明:
    • 工程依赖org.json库,采用的是:org.json ,下载的是源代码,可以打包成json.jar,更方便的使用
    • 工程依赖httpclient,下载地址:httpclient ,使用可以查看它提供的手册
    • 工程还依赖struts2提供的某些jar包,记得添加

最终效果

技术分享
技术分享

PS:

一些问题记录:

参考资源

一天教你入门struts2

标签:struts2   javaweb   ip库   

原文地址:http://blog.csdn.net/zy416548283/article/details/46373447

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