2016-10-11 1 views
-2

그래서 저는 HTML, CSS 및 프레임 워크에 일반적으로 익숙해 져 있으며 Java에 대한 올바른 이해를 가지고 있습니다. 그러나, 나는 당신이 HTML 파일에 추가하는 Javascript로 inbuilt 함수와 계산을 만드는 방법을 알 수 있습니다. 하지만 웹 사이트에서 데이터 및 정보를 가져올 컴퓨터의 Java 프로그램이 어떻게 작동하는지 이해할 수 없습니다. 아무도 그것을 설명 할 수 있습니까? 인터넷에서 좋은 답변을 찾을 수 없었습니다.데이터베이스 서버 및 공용 웹 사이트 통신

말해 자바에서 서버로 2 + 3 값을 계산하고 그 값을 가져 와서 웹 사이트에 표시하고 싶다고 말하십시오. 내가 어떻게 그럴 수 있니?

<a href="#" onclick = 'shipProduct(1)'>Test</a> 

이 링크를 :

당신이 링크가 말 : 여기 서버에서 자바 서블릿 자바 스크립트를 통해 아약스 요청을 전송하여이 기능을 달성

답변

1

은 내가 사용하는 예입니다 I이었다 했는가

/** 
* 
* @param {type} action 
* @param {type} bundleId 
* @returns {undefined} 
*/ 
function shipProduct(bundleId) 
{ 

    $.ajax 
      ({ 
       url: "/FlcErp-war/ShipmentServlet", //this is the name of the serverlet in your project 
       type: "GET", // the type of your request 
       data: _action + "=addToShipped&bundleId=" + bundleId, 
       success: function (content) 
       { 
        if (content.substring(0, 1) == '_') 
        { 
         alert(content); 
        } 
        else 
        { 
         //rebuild shipment tables to show updated 
         //information about the item 
         buildShipmentQueue(); 
        } 

       }, 
       error: function (xhr, status, error) { 
        alert(xhr.responseText); 
        alert(status); 
        alert(error); 
       } 
      }); 
} 

내 요청을 처리 할 수있는 주석 자바 서블릿을 가지고있다 : 내 경우에 해당에 javscript 기능을 찾을 것입니다 클릭 :

당신의 doPost와의 doGet 귀하의 게시물을 처리하고 (다른 독자) 그냥 참고로 요청을

/** 
* 
* @author samo 
*/ 
@WebServlet("/ShipmentServlet") 
public class ShipmentServlet extends HttpServlet { 



    private static final long serialVersionUID = 1L; 

    private static final String _addToShipped = "addToShipped"; 

    private static final String _bundleId = "bundleId"; 

    private static final String _shipmentId = "shipmentId"; 

    private static final String _productId = "productId"; 

    private static final String _updateQueue = "updateQueue"; 

    private static final String _unship = "unship"; 

    private static final String _setInSession = "setInSession"; 

    private static final String _externalBundleId = "externalBundleId"; 

    private static final String _plywood = "P"; 

    private static final String _veneer = "V"; 

    private static final String _lumber = "L"; 

    private static final String _bundle = "Bundle"; 

    private static final String _list = "List"; 

    private boolean multipleActions; 

    private String[] actions; 

    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
    * methods. 
    * 
    * @param request servlet request 
    * @param response servlet response 
    * @throws ServletException if a servlet-specific error occurs 
    * @throws IOException if an I/O error occurs 
    */ 
    protected void processBundleRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException, NamingException, CloneNotSupportedException { 
     response.setContentType("text/html;charset=UTF-8"); 
     try (PrintWriter out = response.getWriter()) { 
      this.actions = null; 

      //this is where we will get the actions to process 
      //if there is more than one action the string will contain 
      // a comma as a delimiter 
      String action = request.getParameter("_action"); 
      InitialContext ctx = new InitialContext(); 

      LoadShipmentController lsc = (LoadShipmentController) ctx.lookup("loadShipmentController"); 
      switch (action) { 
       case _addToShipped: 
        shipProduct(request, out); 
        break; 
       case _updateQueue: 
        Shipment shipment = lsc.getCurrent(); 
        String type = shipment.getShipmentType(); 
        String shipmentQueue = ""; 
        switch (type) { 
         case _veneer: 
          shipmentQueue = lsc.getVeneerShipmentQueue(); 
          break; 
         case _plywood: 
          shipmentQueue = lsc.getShipmentQueue(); 
          break; 
         case _lumber: 
          shipmentQueue = lsc.getShipmentQueue(); 
          break; 
        } 

        out.println(shipmentQueue); 
        break; 
       case _unship: 
        unshipProduct(request, out); 
        break; 

       case _setInSession: 
        String bundleId = request.getParameter(_bundleId); 
        lsc.setBundleId(bundleId); 
        break; 
       case _list: 
        out.println(lsc.getBundleAndProductListString()); 
        break; 

       // setSessionVariable(_externalBundleId, bundleId); 
      } 
     } 
    } 

    public void shipProduct(HttpServletRequest request, PrintWriter out) throws NamingException, CloneNotSupportedException { 
     Integer bundleId = Integer.valueOf(request.getParameter(_bundleId)); 
     InitialContext ctx = new InitialContext(); 

     ShipmentController shipmentController = (ShipmentController) ctx.lookup("shipmentController"); 
     LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController"); 

     // getting the product from the bundle, because that's all we care about 

     Product product = shipmentController.loadBundle(bundleId).getProduct(); 

     String type = product.getProductType(); 

     //because the way we ships differs depending on the product type I need to 
     //check first mainly for veneer shipments because their bundle count is not 
     //predetermined 
     boolean loaded = false; 

     switch (type) { 
      case _veneer: 
       loaded = loadShipmentController.loadVeneerProduct(product, bundleId); 
       break; 
      case _plywood: 
       loaded = loadShipmentController.loadPlywoodProduct(product, bundleId); 
       break; 
      case _lumber: 
       loaded = loadShipmentController.loadLumberProduct(product, bundleId); 
       break; 
     } 

     if(!loaded) 
     { 
      out.println("_" + loadShipmentController.getErrors()); 
     } 

    } 

    public void unshipProduct(HttpServletRequest request, PrintWriter out) throws NamingException { 
     Integer bundleId = Integer.valueOf(request.getParameter(_bundle)); 
     InitialContext ctx = new InitialContext(); 

     LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController"); 


     boolean unship = loadShipmentController.unshipByBundleId(bundleId); 

     if (!unship) { 
      String error = loadShipmentController.getErrors(); 
      out.println("Error:" + error); 
     } 

    } 

    private void setSessionVariable(String name, String value) { 

     FacesContext context = FacesContext.getCurrentInstance(); 
     ExternalContext externalContext = context.getExternalContext(); 
     HttpSession session = (HttpSession) externalContext.getSession(false); 
     session.setAttribute(name, value); 
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
    /** 
    * Handles the HTTP <code>GET</code> method. 
    * 
    * @param request servlet request 
    * @param response servlet response 
    * @throws ServletException if a servlet-specific error occurs 
    * @throws IOException if an I/O error occurs 
    */ 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     try { 
      processBundleRequest(request, response); 
     } catch (NamingException ex) { 
      Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (CloneNotSupportedException ex) { 
      Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    /** 
    * Handles the HTTP <code>POST</code> method. 
    * 
    * @param request servlet request 
    * @param response servlet response 
    * @throws ServletException if a servlet-specific error occurs 
    * @throws IOException if an I/O error occurs 
    */ 
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    } 


} 
+1

을 얻을 것이다, Ajax 요청이 ** 한 ** 그것을하는 방법이 아니라 유일한 방법 . – ochi

관련 문제