java后台的跨域问题

    xiaoxiao2022-06-30  144

    //网站A跨域访问网站B的某个方法并返回 //这是网站A的后台 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throwsIOException { String json_string = "{'mes':null,'error':false}"; response.setCharacterEncoding("utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); try { String basePath = request.getParameter("basePath"); String username = request.getParameter("username"); String password = request.getParameter("password"); json_string=login_(basePath,username,password); }catch (Exception e){ } response.getWriter().print(json_string); return ; } public String login_(String basePath,String userName,String password)throws Exception{ URL realUrl = new URL(basePath); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("POST"); // 设置请求方式 conn.setDoOutput(true);// 是否输入参数 StringBuffer params = new StringBuffer(); // 表单参数与get形式一样 params.append("username").append("=") .append(URLEncoder.encode(userName, "utf-8")).append("&") .append("password").append("=").append(password); byte[] bypes = params.toString().getBytes(); conn.getOutputStream().write(bypes);// 输入参数 InputStream inStream=conn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) !=-1 ){ outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray();//网页的二进制数据 outStream.close(); inStream.close(); //处理中文乱码并返回json数据 return new String(data, "utf-8"); } //这是网站B中被跨域访问的方法 //接收从网站A传过来的用户名和密码,验证用户名密码是否正确并返回结果 private final static ObjectMapper objectMapper = new ObjectMapper(); protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); LoginMessage lm = new LoginMessage(); lm.error = true; if ( !"true".equals(request.getParameter("isdemo")) && SecurityUtils.getSubject().isAuthenticated()) { lm.mes = "当前会话已经是验证通过了的."; lm.error = false; } else { if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) { lm.mes = "用户名或密码不能为空."; } else { UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { SecurityUtils.getSubject().login(token); lm.error = false; } catch (AuthenticationException e) { if (e instanceof LockedAccountException) { lm.mes = "用户密码不正确."; } else { lm.mes = Throwables.getRootCause(e).getMessage(); } } catch (Exception e) { e.printStackTrace(); lm.mes = Throwables.getRootCause(e).getMessage(); } } } response.setCharacterEncoding("utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = response.getWriter(); out.println(objectMapper.writeValueAsString(lm));//返回jsonp格式数据 out.flush(); out.close(); } static class LoginMessage { public String mes; public boolean error; }

     


    最新回复(0)