jsp基础练习(求圆的面积)

程序小白,希望和大家多交流,共同学习
第一个jsp+servlet,网页版的计算圆的面积
jsp基础练习(求圆的面积)_第1张图片
服务器

package servlet.demo;

public class Service 
{
    public double computeArea(double radius)
    {
        return radius * radius * Math.PI;
    }
}
package servlet.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ComputeArea extends HttpServlet
{
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        HttpSession session = request.getSession(true);
        //获取半径
        String str = (String)request.getParameter("radius");
        //处理半径
        if (str.equals("") || str == null)
        {
            str = "0";
        }
        //保存半径
        session.setAttribute("radius", str);
        //计算面积
        double radius = Integer.parseInt(str);
        Service service = new Service();
        double area = service.computeArea(radius);
        //计算面积
        String result = String.format("%.3f", area);
        session.setAttribute("area", result);
        //重定向
        response.sendRedirect("index.jsp");
    }
}

web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0" metadata-complete="true">

    <servlet>
        <servlet-name>areaservlet-name>
        <servlet-class>servlet.demo.ComputeAreaservlet-class>
    servlet>

    <servlet-mapping>
        <servlet-name>areaservlet-name>
        <url-pattern>/getAreaurl-pattern>
    servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>

web-app>

页面

<%@ page language="java" contentType="text/html; charset=GB2312" %>  
<html>
    <head> head>
    <body style="background:cyan">
    <center>
        <%
            String radius = (String)session.getAttribute("radius");
            String area = (String)session.getAttribute("area");
            out.println("用户传递的半径为:" + radius + ",计算面积为:" + area);
        %>

        <form action="getArea" onsubmit="return check()">
            输入圆的半径:<input type="text" name="radius" value="0"/>
            <input type="submit" value="计算" name="submit" />
        form>
    center>
    body>
html>

你可能感兴趣的:(JSP)