MVC pattern
The main task of the model is to help developers solve a class of problems.
The MVC pattern is primarily used to plan the development of your site in a basic structure.
The servlet remembers to act as a controller layer. Cn.itcast.controller
The Java class primarily handles business logic. Cn.itcast.bean
JSP is mainly responsible for the data page display.
There is absolutely no need to use the above three technologies for a more traditional and less complex web application. You can therefore use Jsp+javabean direct processing.
Case One: Web Calculator
1. Edit a cal.jsp page
<body> <!--creating JavaBean objects--<jsp:usebean id="Calculator" class="Cn.itcast.beans.Calculator"Scope="page"></jsp:useBean> <!--Package User data--<jsp:setproperty name="Calculator"property="*"/> <!--calculation Results-<%Try{calculator.calculate (); }Catch(Exception e) {//Store the exception object in the page fieldPagecontext.setattribute ("msg", E); } %> <form action="/day09/cal.jsp"Method="Post"> <table align="Center"Border="1"> <tr align="Center"> <TD colspan="2">web Calculator </td> </tr> <tr> <td> operand 1:</td> < Td><input type="text"Name="NUM1"></td> </tr> <tr> <td> operator:</td> <t D> <SelectName="option"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </Select> </td> </tr> <tr> <td> operand 2:</td> <td><input type="text"Name="num2"></td> </tr> <tr align="Center"> <TD colspan="2"><input type="Submit"Value="Calculation"></td> </tr> </table> </form> <br/> calculation Result:<!--get the value in JavaBean-<jsp:getproperty name="Calculator"property="NUM1"/> <jsp:getproperty name="Calculator"property="option"/> <jsp:getproperty name="Calculator"property="num2"/> = <jsp:getproperty name="Calculator"property="result"/> error message:<%Exception Exp= (Exception) Pagecontext.getattribute ("msg"); if(exp! =NULL){ out. Write (Exp.getmessage ()); } %> 2. Write a calculator for the business logic class Calculator.java
Public classCalculator {//Specifying Properties Private DoubleNUM1 =0.0; Private Charoption ='+'; Private Doublenum2 =0.0; Private Doubleresult =0.0; //provide a way to calculate Public voidcalculate () {Switch( This. Option) { Case '+': This. result = This. NUM1 + This. num2; Break; Case '-': This. result = This. NUM1- This. num2; Break; Case '*': This. result = This. NUM1 * This. num2; Break; Case '/': if( This. num2 = =0){ Throw NewRuntimeException ("dividend cannot be 0"); } This. result = This. NUM1/ This. num2; Break; } //processing (rounding) of calculated resultsBigDecimal big =NewBigDecimal ( This. Result); //OperationBig = Big.setscale (3, BIGDECIMAL.ROUND_HALF_UP); //Take good data out of Operation This. result =Big.doublevalue (); }}
The above code in the JSP directly appear in the business logic, it is not convenient for the post-maintenance of the artist, the above MVC pattern is not recommended to use.
Java Learning Note-web Calculator (36)