Cubica

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Cubica</title>
    </head>
    <body>
        <h1>Cubica</h1>
        <p>y = a x³ + b x² + c x + d</p>
        <form action="index.jsp" method="get">
            a = <input type="text" name="a"/><br/>
            b = <input type="text" name="b"/><br/>
            c = <input type="text" name="c"/><br/>
            d = <input type="text" name="d"/><br/>
            <input type="submit" value="Disegna" />
        </form>
        <p><img width="400" height="400" src="grafico?a=<%=request.getParameter("a")%>&b=<%=request.getParameter("b")%>&c=<%=request.getParameter("c")%>&d=<%=request.getParameter("d")%>" /></p>
    </body>
</html>

grafico.java

double a = 0.0, b = 0.0, c = 0.0, d = 0.0;

private double f(double x) {
    return a * x * x * x + b * x * x + c * x + d;
}

private int xg(double x) {
    return 200 + (int) Math.round(x * 40.0);
}

private int yg(double y) {
    return 200 - (int) Math.round(y * 40.0);
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/png");
    try (OutputStream os = response.getOutputStream()) {
        // crea l'immagine
        BufferedImage img = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.createGraphics();
        // cancella lo sfondo
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 400, 400);
        // disegna gli assi cartesiani
        g.setColor(Color.BLACK);
        g.drawLine(0, 200, 400, 200);
        g.drawString("X", 390, 190);
        g.drawLine(200, 0, 200, 400);
        g.drawString("Y", 210, 10);
        try {
            // legge i parametri
            a = Double.parseDouble(request.getParameter("a"));
            b = Double.parseDouble(request.getParameter("b"));
            c = Double.parseDouble(request.getParameter("c"));
            d = Double.parseDouble(request.getParameter("d"));
            // visualizza i parametri
            g.drawString("a = " + a, 0, 20);
            g.drawString("b = " + b, 0, 40);
            g.drawString("c = " + c, 0, 60);
            g.drawString("d = " + d, 0, 80);
            // disegna il grafico
            g.setColor(Color.BLUE);
            for (double x = -10.0; x < 10.0; x += 0.001) {
                double y = f(x);
                g.drawLine(xg(x), yg(y), xg(x), yg(y));
            }
        } catch (Exception e) {
            g.drawString("Alcuni parametri mancanti", 0, 20);
            g.drawString("o non inseriti correttamente", 0, 40);
        }
        // invia l'immagine in output
        ImageIO.write(img, "png", os);
        os.close();
    }
}