By GokiSoft.com| 19:39 28/09/2020|
Java Web + WebService

[Share Code] Chia sẻ code Web Service - Web Application

Web Service

#CalculatorWS.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ws;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

/**
 *
 * @author Admin
 */
@WebService(serviceName = "CalculatorWS")
public class CalculatorWS {
    @WebMethod
    public float plus(@WebParam(name = "x") float x, @WebParam(name = "y") float y) {
        return x+y;
    }
    
    @WebMethod
    public float minus(@WebParam(name = "x") float x, @WebParam(name = "y") float y) {
        return x - y;
    }
    
    @WebMethod
    public float multiple(@WebParam(name = "x") float x, @WebParam(name = "y") float y) {
        return x*y;
    }
    
    @WebMethod
    public float devide(@WebParam(name = "x") float x, @WebParam(name = "y") float y) throws Exception {
        if(y==0) {
            throw new Exception("Devide by Zero!!!");
        }
        return x/y;
    }
}

Web Application


#CalculatorAPI.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package api;

import ws.Exception_Exception;

/**
 *
 * @author Admin
 */
public class CalculatorAPI {

    public static float plus(float arg0, float arg1) {
        ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
        ws.CalculatorWS port = service.getCalculatorWSPort();
        return port.plus(arg0, arg1);
    }

    public static float minus(float arg0, float arg1) {
        ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
        ws.CalculatorWS port = service.getCalculatorWSPort();
        return port.minus(arg0, arg1);
    }

    public static float multiple(float arg0, float arg1) {
        ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
        ws.CalculatorWS port = service.getCalculatorWSPort();
        return port.multiple(arg0, arg1);
    }

    public static float devide(float arg0, float arg1) throws Exception_Exception {
        ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
        ws.CalculatorWS port = service.getCalculatorWSPort();
        return port.devide(arg0, arg1);
    }
    
}


#CalculatorServlet.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import api.CalculatorAPI;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ws.Exception_Exception;

/**
 *
 * @author Admin
 */
public class CalculatorServlet extends HttpServlet {

    // <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 {
        float x = 0, y = 0, result = 0;
        String cal = "";

        if (request.getParameter("x") != null) {
            x = Float.parseFloat(request.getParameter("x"));
        }
        if (request.getParameter("y") != null) {
            y = Float.parseFloat(request.getParameter("y"));
        }
        if (request.getParameter("cal") != null) {
            cal = request.getParameter("cal");
        }
        if (!cal.isEmpty()) {
            switch (cal) {
                case "+":
                    result = CalculatorAPI.plus(x, y);
                    break;
                case "-":
                    result = CalculatorAPI.minus(x, y);
                    break;
                case "*":
                    result = CalculatorAPI.multiple(x, y);
                    break;
                case "/": {
                    try {
                        result = CalculatorAPI.devide(x, y);
                    } catch (Exception_Exception ex) {
                        Logger.getLogger(CalculatorServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                break;
            }
        }

        request.setAttribute("x", x);
        request.setAttribute("y", y);
        request.setAttribute("cal", cal);
        request.setAttribute("result", result);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/calculator.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * 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 {
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


#calculator.jsp


<%-- 
    Document   : calculator
    Created on : Sep 28, 2020, 6:42:56 PM
    Author     : Admin
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Registation Form * Form Tutorial</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Calculator</h2>
			</div>
			<div class="panel-body">
                            <form method="get">
				<div class="form-group">
				  <label for="x">X:</label>
                                  <input required="true" type="number" step="0.01" class="form-control" id="x" name="x" value="${x}">
				</div>
				<div class="form-group">
				  <label for="y">Y:</label>
                                  <input required="true" type="number" class="form-control" id="y" name="y" step="0.01" value="${y}">
				</div>
                                <h2>
                                    Result: ${result}
                                </h2>
                                <button class="btn btn-success" name="cal" value="+">+</button>
                                <button class="btn btn-success" name="cal" value="-">-</button>
                                <button class="btn btn-success" name="cal" value="*">*</button>
                                <button class="btn btn-success" name="cal" value="/">/</button>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)