Using JSP call JavaBean implement a simple Web Calculator sample _jsp programming

Source: Internet
Author: User

Here is the code:


Calculator.java
Copy the code:

package com.amos.model;
import java.math.BigDecimal;

/ **
* @ClassName: Calculator
* @Description: calculator
* @author: amosli
* @email: amosli@infomorrow.com
* @date Mar 20, 2014 1:04:59 AM
* /
public class Calculator {
    private String firstnum = "0";
    private String secondnum = "0";
    private char operator = '+';
    private String result;

    public String getResult () {
        return result;
    }

    public char getOperator () {
        return operator;
    }

    public void setOperator (char operator) {
        this.operator = operator;
    }

    public void setResult (String result) {
        this.result = result;
    }

    public String getFirstnum () {
        return firstnum;
    }

    public void setFirstnum (String firstnum) {
        this.firstnum = firstnum.trim ();
    }

    public String getSecondnum () {
        return secondnum;
    }

    public void setSecondnum (String secondnum) {
        this.secondnum = secondnum.trim ();
    }

    public void calculate () {
        BigDecimal a = new BigDecimal (this.firstnum);
        BigDecimal b = new BigDecimal (this.secondnum);
        switch (this.operator) {
        case '+':
            this.result = a.add (b) .toString ();
            break;
        case '-':
            this.result = a.subtract (b) .toString ();
            break;
        case '*':
            this.result = a.multiply (b) .toString ();
            break;
        case '/':
            if (b.doubleValue () == 0) {
                throw new RuntimeException ("The dividend cannot be zero");
            }
            this.result = a.divide (b, 10, BigDecimal.ROUND_HALF_DOWN) .toString ();
            break;
        default:
            break;
        }
    }
}
calculator.jsp

Copy the code:

<% @ page language = "java" contentType = "text / html; charset = UTF-8"
    pageEncoding = "UTF-8"%>
<! DOCTYPE html PUBLIC "-// W3C // DTD HTML 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8">
<title> jsp calculator </ title>
</ head>
<body>
    <jsp: useBean id = "calcBean" class = "com.amos.model.Calculator"> </ jsp: useBean>
    <jsp: setProperty property = "*" name = "calcBean" />
    <%
        calcBean.calculate ();
    %>
    <hr>
    The calculation result is:
    <jsp: getProperty property = "firstnum" name = "calcBean" />
    <jsp: getProperty property = "operator" name = "calcBean" />
    <jsp: getProperty property = "secondnum" name = "calcBean" />
    = <jsp: getProperty property = "result" name = "calcBean" />
    <hr>
    <form action = "/ jsp / calculator.jsp" method = "post">
        <table style = "text-align: center;">
            <tr>
                <td colspan = "2"> Simple calculator </ td>
            </ tr>
            <tr>
                <td> First parameter </ td>
                <td> <input type = "text" name = "firstnum" /> </ td>
            </ tr>
            <tr>
                <td> <select name = "operator">
                        <option value = "+"> + </ option>
                        <option value = "-">-</ option>
                        <option value = "*"> * </ option>
                        <option value = "/"> / </ option>
                </ select> </ td>
            </ tr>
            <tr>
                <td> The second number </ td>
                <td> <input type = "text" name = "secondnum" /> </ td>
            </ tr>
            <tr>
                <td>
                    <button name = "calc" type = "submit"> Calculate </ button>
                </ td>
            </ tr>
        </ table>
    </ form>
</ body>
</ html>
Code introduction

1) Note here that if you want to perform precision calculations, it is easy to distort with double + double, for example, a = 0.1, b = 0.02, a + b =?
Copy the code:

0.1 + 0.02 = 0.12000000000000001
This is because the bottom layer of the computer only knows 0 and 1, and double is 64-bit precision, so it is easy to distort when calculating.

It is recommended to use the BigDecimal or BigInteger class to perform operations, and call its original add, substract and other methods to implement operations such as addition and subtraction.

2) jsp: useBean is used to instantiate objects, and jsp: setProperty and jsp: getProperty are used to set and take values.

3) About the configuration of the error page content:

Add the following to web.xml to capture the exception:

Copy the code:

<error-page>
      <exception-type> java.lang.Exception </ exception-type>
      <location> /error/error.jsp </ location>
  </ error-page>
At the same time, the error information is displayed in the error.jsp page:

Copy the code:

sorry, something went wrong !!
    <% out.print (exception.getMessage ());%>
Added: JSP has two development modes:

After Sun introduced JSP technology, it also recommended two web application development modes, one is JSP + JavaBean mode, and the other is Servlet + JSP + JavaBean mode.
1) JSP + JavaBean mode, suitable for simple development, suitable for developing web applications with less complicated business logic. In this mode, JavaBean is used to encapsulate business data. JSP is responsible for processing user requests and displaying data;
2) The Servlet + JSP + JavaBean (MVC) pattern is suitable for developing complex web applications. In this model, the servlet is responsible for processing user requests, jsp is responsible for data display, and javabean is responsible for encapsulating data. Servlet + JSP, JavaBean mode program between the various modules is clear, web development recommends this mode.

The first development model is used in this example.

PS: Here are two more online calculators on this site, both implemented in js and powerful. I believe it will be helpful for everyone to understand JavaScript mathematical operations and web design:

Online standard calculator: http://tools.jb51.net/jisuanqi/jsq

Online scientific calculator: http://tools.jb51.net/jisuanqi/jsqkexue


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.