jsp에서javabean을 활용

2813 단어
간단한 계산 기능의javabean을 jsp에 삽입합니다.javabean 코드는 다음과 같습니다.
    
4
package com.shizhan;

public class Computer {
	private double shu1;
	private double shu2;
	private String operate;
	
	public Computer() {
		
	}
	
	public Computer(double shu1, double shu2, String operate) {
		super();
		this.shu1 = shu1;
		this.shu2 = shu2;
		this.operate = operate;
	}

	public double getShu1() {
		return shu1;
	}
	public void setShu1(double shu1) {
		this.shu1 = shu1;
	}
	public double getShu2() {
		return shu2;
	}
	public void setShu2(double shu2) {
		this.shu2 = shu2;
	}
	public String getOperate() {
		return operate;
	}

	public void setOperate(String operate) {
		this.operate = operate;
	}

	public double computer()
	{
		if(operate.equals("+"))
		{
			return shu1+shu2;
		}
		if(operate.equals("-"))
		{
			return shu1-shu2;
		}
		if(operate.equals("*"))
		{
			return shu1*shu2;
		}
		if(operate.equals("/"))
		{
			return shu1/shu2;
		}
		return 0;
	}
}
jsp의 코드는 다음과 같습니다.
 
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

  </head>
  
  <body>
   <jsp:useBean id="computer" class="com.shizhan.Computer"></jsp:useBean>
   <form action="" method="post">
                       1<input type="text" name="shu1"/><BR>
        <select name="operate">
           <option  value="+">+</option>
           <option  value="-">-</option>
           <option  value="*">*</option>
           <option  value="/">/</option>
        </select>        
                       2<input type="text" name="shu2"/>  
        <input type="submit" name="avas" value="  ">
    </form>
   
   <jsp:setProperty property="*" name="computer"/>
    <%
       double res;
       if(request.getParameter("shu1")!=null && request.getParameter("shu2")!=null)
       {
          res=computer.computer();
    %>
             <input type="text" name="res" value=
           <%=res%>
           ><BR>  
    <%
       }
       else
       {
    %>
           <input type="text" name="res" ><BR>  
    <%
       }
    %>
 
  </body>
</html>

좋은 웹페이지 즐겨찾기