http方式的post跳转和get跳转(js->java->java)

在做项目的时候,经常会涉及到页面跳转问题,或者是后台不同工程之间的访问问题,那么这个时候就会有一个问题了前后台怎么跳转,后台工程之间怎么访问。废话太多了,直接看代码吧。

前后台之间访问

前后台之间访问方式很多,有ajax,post,get,dwr等,这边笔者关注的是参数传递问题。
引用之前的一篇文章《ajax整合struts2,spring传递复杂json对象》
这篇文章有教大家怎么传递,下面这篇文章的关键代码:

public Map<String, Object> query(String param){  
    OrderBean orderBean = (OrderBean)jsonUtil.toObject(param, OrderBean.class);//这边使用jsonutil工具进行json字符串转对象操作,具体代码下附  
    return null;  
}
public String toUTF8(String jsonStr){  
        try {  
            return URLDecoder.decode(jsonStr,"utf-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return null;  
    } 

通常经过了toUTF8(String jsonStr)方法,前台传过来的url编码参数就可以正常变成字符串,如果我们访问只到这边,这样的操作就足够了,问题出现了,这个时候如果想要在此处,把这个参数通过http方式传递到另外一个系统呢,那么这个时候要做的就不是url编码转码成utf-8了,而是还要进一步的在传过来的url编码的参数基础上继续url转码一次。直接附上不同系统之间的后台访问的代码了:

主动访问端后台请求代码

    /**
     * http方式远程访问另外一个系统的服务
     * @param name 参数,前台传来的,可以是复杂的对象json字符串
     */
    public void httpRedirect(String param){
        //通过读取配置文件获取url,解耦
        PropertiesUtil propertiesUtil = new PropertiesUtil("/config/unifiedConfig.properties");
        try{
            //根据key读取properties文件中的value
                String urlStr = propertiesUtil.readValue("agencyMgrServiceUrl");
                //关键:将页面传来的参数再一次的url编码格式转码
                urlStr += "?param="+jsonUtil.encoder(param);
                URL url = new URL(urlStr);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);    // 可以发送数据
                conn.setDoInput(true);    // 可以接收数据
                conn.setRequestMethod("POST");    // POST方法
                // 必须注意此处需要设置UserAgent,否则google会返回403
                conn.setRequestProperty
                ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.connect();
                conn.getOutputStream();
//              //    写入的POST数据
                OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                osw.flush();
                osw.close();
                // 读取响应数据
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String s;
                while ((s = in.readLine()) != null)
                    System.out.println(s);
        }catch (Exception e) {
            e.printStackTrace();
        }
            }

propertiesutil文件代码

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 *类描述:
 *@author: a涛
 *@date: 日期:2017-3-13 时间:下午4:29:36
 *@version 1.0
 */
public class PropertiesUtil {
    //配置文件的路径
    private String configPath=null;

    /**
     * 配置文件对象
     */
    private Properties props=null;

    /**
     * 默认构造函数,用于sh运行,自动找到classpath下的config.properties。
     */
    public PropertiesUtil() throws IOException{
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties");
            props = new Properties();

            props.load(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(in!=null)
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        //关闭资源
    }

    /**
     * 有参构造函数
     * @param fllepath 配置文件存放的路径
     * @throws IOException
     */
    public PropertiesUtil(String filepath){
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getClassLoader().getResourceAsStream(filepath);
            props = new Properties();

            props.load(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(in!=null)
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        //关闭资源

    }

    /**
     * 根据key值读取配置的值
     * @param key key值
     * @return key 键对应的值 
     * @throws IOException 
     */
    public String readValue(String key) throws IOException {
        return  props.getProperty(key);
    }

    /**
     * 读取properties的全部信息
     * @throws FileNotFoundException 配置文件没有找到
     * @throws IOException 关闭资源文件,或者加载配置文件错误
     * 
     */
    @SuppressWarnings("rawtypes")
    public Map<String,String> readAllProperties() throws FileNotFoundException,IOException  {
        //保存所有的键值
        Map<String,String> map=new HashMap<String,String>();
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String Property = props.getProperty(key);
            map.put(key, Property);
        }
        return map;
    }

    /**
     * 设置某个key的值,并保存至文件。
     * @param key key值
     * @return key 键对应的值 
     * @throws IOException 
     */
    public void setValue(String key,String value) throws IOException {
        Properties prop = new Properties();
        InputStream fis = new FileInputStream(this.configPath);
        // 从输入流中读取属性列表(键和元素对)
        prop.load(fis);
        // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
        // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream fos = new FileOutputStream(this.configPath);
        prop.setProperty(key, value);
        // 以适合使用 load 方法加载到 Properties 表中的格式,
        // 将此 Properties 表中的属性列表(键和元素对)写入输出流
        prop.store(fos,"last update");
        //关闭文件
        fis.close();
        fos.close();
    }

    public static void main(String[] args) {
        PropertiesUtil p;
        try {
            p = new PropertiesUtil("config/settings.properties");
            System.out.println(p.readAllProperties());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

被访问端后台接受请求代码

    public void httpPostAccept(String param){
        try {
            agencyIn = (AgencyIn) jsonUtil.toObject(jsonUtil.toUTF8(param), AgencyIn.class);
//          agencyIn = (AgencyIn) jsonUtil.toObject(new String(param.getBytes("iso-8859-1"),"utf-8"), AgencyIn.class);//"这种方式等同上面方式,都可以把url编码格式转成utf-8"
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

至此,代码分享完毕。有问题,可以联系笔者。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独行侠_阿涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值