我是靠谱客的博主 虚幻胡萝卜,最近开发中收集的这篇文章主要介绍登录功能(调用接口),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

项目实例学习

用户登录时发送用户名和密码到其他平台进行校验,并将结果返回到本系统进行处理。

①首页html中,运用ajax实现异步

	    //获取项目名
	function sysName(){
		var pathName =  window.document.location.pathname;
		var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
		return (projectName);
	}
	function get_time() {
  		 return new Date().getTime();
	}
	    $.ajax( {
	        url : sysName()+"/Server?code=login&time"+get_time(),
	        type : "POST",
	        async : false,
	        data : {
				"userId" : theForm.UserID.value,
				"password" : pwdResult
			},
	        success : function(data) {
	            var obj = {};
	            obj = JSON.parse(data);
	            success = obj.success;
	            pwdtype = obj.pwdtype;
	            ErrorCode = obj.ErrorCode;
	            message = obj.message;
	        	if(success=='true'){	        		
					//处理业务逻辑
				}else{			
					//处理业务逻辑
				}																			
				
	        }
	    });

②xml中配置servlet

<servlet>
	<servlet-name>Server</servlet-name>
	<servlet-class>com.*.app.*.Server</servlet-class> //实现类的详细路径
</servlet>
<servlet-mapping>
	<servlet-name>Server</servlet-name>
	<url-pattern>/Server</url-pattern>
</servlet-mapping>	

③Server中实现

public class Server extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
        String code = request.getParameter("code");
        String output = "";
        XXService xs= new XXService();
        //操作员登录信息验证
        if(StringUtils.equals(code,"login")){
        	String userId = request.getParameter("userId");
            String passWord = request.getParameter("password");
            try {
            	 output = xs.login(userId,passWord);
            } catch (DecoderException e) {
                e.printStackTrace();
            }
        }
        if(StringUtils.isNotEmpty(output)){
            response.getWriter().print(output);
        }else{
            response.getWriter().print("nothing");
        }
}

④XXService中实现

    public String login(String userId,String passWord) throws DecoderException, UnsupportedEncodingException {    	
        	Map <String,String> logonE=EUtil.logonVerify(userId, passWordSM2); 
        	String [] keys = {"success","pwdtype","ErrorCode","message"};
            String [] values = {loginE.get("success"),loginE.get("pwdtype"),loginE.get("ErrorCode"),loginE.get("message")};
        	return creatJsonString(keys,values);
    	}        
    }
     /**
     * 创建Json的字符串
     * @param key
     * @param value
     */
    public  String creatJsonString(String[] key,String[] value) {
        JsonObject jsonObject = new JsonObject();
        for(int i = 0;i<key.length;i++){
            jsonObject.addProperty(key[i], value[i]);
        }
        return jsonObject.toString();
    }

⑤EUtil对接收的报文进行处理

public class EUtil {
	/**
	 * 登录验证
	 * @param userId 登录用户账号
	 * @param password 密码
	 * @throws Exception
	 */
	public static Map<String,String> logonVerify(String userId,String password){				
		Map<String,String> resultMap = new HashMap<String,String>();   	  
    	ConnectionUtils connUtils = new ConnectionUtils();
    	try {
    		//http://000.000.00.00:8080/RWA/WsHttpReceive
			String messageres=connUtils.sendMessage(connUtils.getConnection("http://localhost:8080/RWA/WsHttpReceive"),connUtils.buildJsonMessage01(userId,password));
			//处理接收消息
			Map<String,Object> receiveJson = JsonUtil.parseJsonMessage(messageres);
			Map<String,Object> esbHeader = (Map<String, Object>) receiveJson.get("ESBHeader");	
			String errorCode=esbHeader.get("ErrorCode").toString();
			String errorMsg=esbHeader.get("ErrorMsg").toString();
			Map<String,Object> appBody = (Map<String, Object>) receiveJson.get("APPBody");				
			String pwdtype=appBody.get("pwdtype").toString();
			String sucmsg=appBody.get("sucmsg").toString();
			if (receiveJson!=null && null != esbHeader) {
				//业务逻辑处理			
		} catch (Exception e) {
			resultMap.put("success","false");
			resultMap.put("message","调用服务异常");
			e.printStackTrace();
		}
    	return resultMap;
	}

⑥ConnectionUtils发送报文和报文内容拼接

public class ConnectionUtils {
	
	/**
	 * 向其他平台发送通知消息
	 * @param conn 连接
	 * @param json 请求数据
	 * @return 接收返回消息
	 * @throws Exception 
	 */
	public String sendMessage(HttpURLConnection conn,String json) throws Exception {
		OutputStream out = null;
		//String msg = null;
		InputStream in = null;
		String message = null;
		try {
			//获取一个输出流用于写入请求数据
			out = conn.getOutputStream();			
			System.out.println("获取一个输出流用于写入请求数据");			
			//发送的数据
			//msg =base64Encoding(json);
			System.out.println("发送的数据"+json);
			//将消息写入请求的输出流中
			out.write(json.getBytes("UTF-8"));
			
			//刷新输出流
			out.flush();
			
			//获取连接的输入流
			in = conn.getInputStream();
			System.out.println("获取连接的输入流");
			//定义一个缓冲数组
			byte[] bytes = new byte[in.available()];
//			
//			//读取数据
			in.read(bytes);
			
			//解码
//			byte[] baseRespByte= Base64.decodeBase64(bytes);
			
			message = new String(bytes, "UTF-8");
		} catch (Exception e) {
			throw new Exception("SERVER:接收远程消息失败!");
		} finally {
			//关闭资源
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
			return message;
	}		
	/**
	 * 获取远程连接对象
	 * @param httpUrl 服务地址
	 * @return
	 * @throws Exception
	 */
	public HttpURLConnection getConnection(String httpUrl) throws Exception {
		HttpURLConnection conn = null;
		try {			
			//生成远程连接对象
			URL url = new URL(httpUrl);			
			//打开链接
			conn = (HttpURLConnection) url.openConnection();			
			//设置请求参数值
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(1000);
			conn.setDoOutput(true);
			conn.setDoInput(true);			
			//返回链接
			return conn;
		} catch (Exception e) {
			throw new Exception("SERVER:获取远程连接失败!");
		}
	}	
	/**
	 * 字符串编码
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static final String base64Encoding(String str) throws UnsupportedEncodingException {
		Base64 base64 = new Base64();
		return base64.encodeToString(str.getBytes("UTF-8"));
	}	
	/**
	 * 关闭远程连接
	 * @param conn
	 */
	public void closeConn(HttpURLConnection conn){
		if (conn != null) {
			conn.disconnect();
		}
	}

	/**
	 * 发送报文
	 * @param account 用户名
	 * @param dctlra  密码
	 */
	public String buildJsonMessage01(String account,String dctlra) throws Exception {
		Date  createDate= new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");//设置日期格式
		SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");//设置日期格式
		String srcDate = dateFormat.format(createDate);
		String srcTime = timeFormat.format(createDate);
		Thread.sleep(1);
		long num=new Date().getTime()-1300000000000L;
		String gloSeqNo="G0431"+srcDate+num;
		Map<String,Object> esbHeaderInformation = new LinkedHashMap<String, Object>();
		esbHeaderInformation.put("ErrorMsg", "");
		esbHeaderInformation.put("ErrorCode", "");	
		Map<String,Object> headerInformation = new LinkedHashMap<String, Object>();
		headerInformation.put("Action", "http://www.cs.cn/22100/012");
		headerInformation.put("Address", "1101");		
		Map<String,Object> appBodyInformation = new LinkedHashMap<String, Object>();
		appBodyInformation.put("dctlra", dctlra);		
		Map<String,Object> esbRequest = new LinkedHashMap<String, Object>();
		esbRequest.put("EsbHeader", esbHeaderInformation);
		esbRequest.put("Header", headerInformation);
		esbRequest.put("APPBody", appBodyInformation);
		String encoding = "GBK";
		byte[] jsonBytes = JsonUtil.buildJsonMessage(esbRequest, encoding);
		return new String(jsonBytes,encoding);
	}
}

⑦测试文件

package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jdk.nashorn.internal.parser.JSONParser;

@WebServlet("/WsHttpReceive")
public class WsHttpReceive extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public WsHttpReceive() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int len = request.getContentLength();
			InputStream is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String buffer = null;
            StringBuffer sb = new StringBuffer();
            while((buffer=br.readLine())!=null){
            	sb.append(buffer+"n");
            }
            System.out.println("原报文:n"+sb.toString().trim());
            PrintWriter out = response.getWriter();
            String jsonString = "返回报文内容";           
            out.write(jsonString);
            System.out.println("发送报文:n"+jsonString);
            out.flush();
            out.close();
		} catch (Exception e) {
            System.out.println("error"+e);
		}
	}

}

最后

以上就是虚幻胡萝卜为你收集整理的登录功能(调用接口)的全部内容,希望文章能够帮你解决登录功能(调用接口)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部