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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cheng_cuo_tuo/article/details/79961972

程序小白,希望和大家多交流,共同学习
第一个jsp+servlet,网页版的计算圆的面积
这里写图片描述
服务器

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

<?xml version="1.0" encoding="UTF-8"?>
<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>area</servlet-name>
        <servlet-class>servlet.demo.ComputeArea</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>area</servlet-name>
        <url-pattern>/getArea</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-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>
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页