Java MVC

MVC标准流程图解

M:

package service;

public class BmiService {
    public String bmi(double height,double weight,String gender){
        String status = "正常";
        double bmi = weight/height/height;//bmi指数等于体重除以身高的平方
        if("m".equals(gender)){
            if(bmi<20){
                status = "过轻";
            }
            if(bmi>25){
                status="过重";
            }
        }else{
            if(bmi<19){
                status = "过轻";
            }
            if(bmi>24){
                status="过重";
            }
        }
        
        return "bmi:"+bmi+"体重状况:"+status;
    }
}

V: 视图

<%@ page contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
    <form action="bmi.do">
        <fieldset>
        
            <legend>计算BMI指数</legend>
            身高(米):<input name="height">
            体重(公斤):<input name="weight">
            性别:男<input type="radio" name="gender" value="m" checked="checked"><input type="radio" name="gender" value="w">
            <input type="submit" value="提交">
        
        </fieldset>
    </form>
</body>
</html>

显示结果页面

<%@ page contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
    ${status }
</body>
</html>

C:控制器

package web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.BmiService;

public class ActionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*控制器的职责:
         * 接收请求,依据请求路径,调用对应的模型来处理
         */
        String uri = request.getRequestURI();//获取资源路径
        String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));//通过处理请求资源路径获取用户的请求
        System.out.println(path);
        if("/bmi".equals(path)){
            String height = request.getParameter("height");
            String weight = request.getParameter("weight");
            String gender = request.getParameter("gender");
            BmiService bmi = new BmiService();
            String status = bmi.bmi(Double.parseDouble(height), Double.parseDouble(weight), gender);
            /*
             * 接收某型返回的结果,调用对应的视图来展现
             */
            request.setAttribute("status", status);
            request.getRequestDispatcher("/WEB-INF/view.jsp").forward(request, response);
        }else if("/toBmi".equals(path)){
            request.getRequestDispatcher("/WEB-INF/bmi.jsp").forward(request, response);//转发写绝对路径
        }
    }

}

结构图:

猜你喜欢

转载自www.cnblogs.com/topzhao/p/10255751.html