【问题标题】:Database server and public website communication [closed]数据库服务器和公共网站通信[关闭]
【发布时间】:2017-02-20 12:11:42
【问题描述】:

所以,我对 html、css 和一般框架有点熟悉,并且对 Java 有相当了解。但是,我只能看到如何使用添加到 html 文件的 Javascript 进行内置函数和计算。但我不明白它是如何与您计算机上的 Java 程序一起工作的,该网站将从中获取数据和信息。谁能解释一下?我在互联网上找不到任何好的答案。

假设我想在服务器上使用 Java 计算值 2+3,然后获取该值并将其显示在网站上。我该怎么做?

【问题讨论】:

    标签: java html database web server


    【解决方案1】:

    我通过 javascript 向服务器上的 java servlet 发送 ajax 请求来实现此功能,这是我使用的一个示例:

    假设你有一个链接:

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

    当点击这个链接时,它会寻找相应的 javscript 函数,在我的例子中是:

        /**
     * 
     * @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);
                    }
                });
    }
    

    我所做的是有一个带注释的 java servlet 来满足我的请求:

    您的 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 {
        }
    
    
    }
    

    【讨论】:

    • 仅供参考(对于其他读者),AJAX 请求是一种的方式,但不是唯一的方式。
    猜你喜欢
    • 2016-02-04
    • 2013-09-02
    • 2020-02-20
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2012-12-04
    • 2018-05-01
    • 2021-09-12
    相关资源
    最近更新 更多