千鋒-模擬實(shí)現(xiàn)SpringMVC功能

SpringMVC
MVC
? m:model:模型,javabean

? v:view:視圖,html/jsp

? c:controller:控制器:servlet

MyMVC模擬實(shí)現(xiàn)
一. 階段一
index.html頁(yè)面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h1>this is index page.</h1>

    <form method="post" action="ProductServlet">
        pid:<input type="text" name="pid" /><br />
        pname:<input type="text" name="pname" /><br />
        price:<input type="text" name="price" /><br />
        img:<input type="text" name="img" /><br />
        <input type="submit" value="submit" /><br />
    </form>
</body>
</html>

ProductServlet.java

package com.qianfeng.controller;

import com.qianfeng.bean.Product;

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

@javax.servlet.annotation.WebServlet(urlPatterns = "/ProductServlet")
public class ProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String pid = request.getParameter("pid");
        String pname = request.getParameter("pname");
        String sprice = request.getParameter("price");
        String img = request.getParameter("img");

        double price = sprice == null ? 0.0 : Double.parseDouble(sprice);

        System.out.println("pid : " + pid);
        System.out.println("price : " + sprice);
        System.out.println("pname : " + pname);
        System.out.println("img : " + img);

        Product p = new Product();

        p.setPid(pid);
        p.setPname(pname);
        p.setImg(img);
        p.setPrice(price);

        request.setAttribute("p", p);

        request.getRequestDispatcher("product.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Product.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>product</title>
</head>
<body>
    <h1>this is product detail page.</h1>

    <%--
        ognl: 對(duì)象導(dǎo)航語(yǔ)言
            user.addr.province;
    --%>
    <h3>pid : ${p.pid}</h3>
    <h3>pname : ${p.pname}</h3>
    <h3>price : ${p.price}</h3>
    <h3>img : ${p.img}</h3>
</body>
</html>

可以實(shí)現(xiàn)頁(yè)面的跳轉(zhuǎn)以及數(shù)據(jù)的展示

問(wèn)題:頁(yè)面都在webapp下,安全性不高

二. 階段二
為了提高程序的安全性,將所有的頁(yè)面都放入webapp/WEB-INF/view目錄下,index.html頁(yè)面無(wú)法直接訪問(wèn),需要專(zhuān)門(mén)建立一個(gè)Sevlet來(lái)訪問(wèn)該頁(yè)面,實(shí)現(xiàn)內(nèi)容請(qǐng)求轉(zhuǎn)發(fā)

新建一個(gè)Servlet來(lái)實(shí)現(xiàn)內(nèi)部轉(zhuǎn)發(fā) ProductInputServlet.java

package com.qianfeng.controller;

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

@WebServlet(urlPatterns = "/ProductInputServlet")
public class ProductInputServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/view/index.html").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

webapp下的WEB-INF/view/index.html頁(yè)面可以直接訪問(wèn),更新ProductServlet.java

package com.qianfeng.controller;

import com.qianfeng.bean.Product;

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

@javax.servlet.annotation.WebServlet(urlPatterns = "/ProductServlet")
public class ProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String pid = request.getParameter("pid");
        String pname = request.getParameter("pname");
        String sprice = request.getParameter("price");
        String img = request.getParameter("img");

        double price = sprice == null ? 0.0 : Double.parseDouble(sprice);

        System.out.println("pid : " + pid);
        System.out.println("price : " + sprice);
        System.out.println("pname : " + pname);
        System.out.println("img : " + img);

        Product p = new Product();

        p.setPid(pid);
        p.setPname(pname);
        p.setImg(img);
        p.setPrice(price);

        request.setAttribute("p", p);

        
        request.getRequestDispatcher("/WEB-INF/view/product.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

三. 階段三,模擬Spring MVC的具體實(shí)現(xiàn)
Controller.java

package com.qianfeng.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定義接口,實(shí)現(xiàn)管理多個(gè)請(qǐng)求,在模擬Spring MVC中的控制器
 */
public interface Controller {

    String handleRequest(HttpServletRequest request, HttpServletResponse response);
}

ProductInputController.java

package com.qianfeng.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductInputController implements Controller {
    @Override
    public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
        return "/WEB-INF/view/index.html";
    }
}

ProductDetailController.java

package com.qianfeng.mvc.controller;

import com.qianfeng.bean.Product;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductDetailController implements Controller {
    @Override
    public String handleRequest(HttpServletRequest request, HttpServletResponse response) {

        String pid = request.getParameter("pid");
        String pname = request.getParameter("pname");
        String sprice = request.getParameter("price");
        String img = request.getParameter("img");

        double price = sprice == null ? 0.0 : Double.parseDouble(sprice);

        System.out.println("pid : " + pid);
        System.out.println("price : " + sprice);
        System.out.println("pname : " + pname);
        System.out.println("img : " + img);

        Product p = new Product();

        p.setPid(pid);
        p.setPname(pname);
        p.setImg(img);
        p.setPrice(price);

        request.setAttribute("p", p);

        return "/WEB-INF/view/product.jsp";
    }
}

DispatcherServlet.java負(fù)責(zé)將多個(gè)請(qǐng)求分發(fā)給各自不同的控制器

package com.qianfeng.mvc.controller;

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

@WebServlet(urlPatterns = {"/ProductInput", "/ProductDetail"})
public class DispatcherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        String action = requestURI.substring(requestURI.lastIndexOf("/") + 1);

        Controller controller = null;

        if("ProductInput".equalsIgnoreCase(action)){
            controller = new ProductInputController();
        }else if("ProductDetail".equalsIgnoreCase(action)){
            controller = new ProductDetailController();
        }

        String url = controller.handleRequest(request, response);

        request.getRequestDispatcher(url).forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

結(jié)論:多個(gè)請(qǐng)求可以交給同一個(gè)Servlet(DispatcherServlet),然后各自不同的請(qǐng)求會(huì)交給各自的控制器。所有請(qǐng)求都叫個(gè)DispatcerServet,該角色相當(dāng)于一個(gè)前端控制器,可以大大的提高客戶的以及服務(wù)器端的工作效率。

四.階段四
給階段三的功能之上添加一個(gè)校驗(yàn)功能

新增一個(gè)ProductForm.java,主要用來(lái)做Product校驗(yàn),struts1有專(zhuān)門(mén)的formbean對(duì)象用來(lái)校驗(yàn)表單數(shù)據(jù),在某些框架中將formbean與bean對(duì)象合二為一了

package com.qianfeng.form;

public class ProductForm {

    private String pname;
    private double price;
    private String img;

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }
}

ProductValidate.java,用來(lái)完成對(duì)于formbean進(jìn)行校驗(yàn),如果校驗(yàn)不通過(guò),則將錯(cuò)誤信息存儲(chǔ)起來(lái)

package com.qianfeng.validate;

import com.qianfeng.form.ProductForm;

import java.util.ArrayList;
import java.util.List;

public class ProductValidate {

    /**
     * 校驗(yàn)給定的ProductForm對(duì)象
     * @param pf 要校驗(yàn)的對(duì)象
     * @return 表單校驗(yàn)不成功,則將錯(cuò)誤信息存儲(chǔ)
     */
    public List<String> validate(ProductForm pf){
        List<String> errors = null;

        String pname = pf.getPname();
        String img = pf.getImg();
        double price = pf.getPrice();

        errors = new ArrayList<>();

        if(pname == null || pname.length() == 0){
            errors.add("product name must not be empty.");
        }


        if(img == null || img.length() == 0){
            errors.add("product image must not be empty.");
        }

        if(price < 0){
            errors.add("the price of product must be a positive number.");
        }

        return errors;
    }
}

更新ProductDetailController.java

package com.qianfeng.mvc.controller;

import com.qianfeng.ProductValidate;
import com.qianfeng.bean.Product;
import com.qianfeng.form.ProductForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ProductDetailController implements Controller {
    @Override
    public String handleRequest(HttpServletRequest request, HttpServletResponse response) {

        String pid = request.getParameter("pid");
        String pname = request.getParameter("pname");
        String sprice = request.getParameter("price");
        String img = request.getParameter("img");

        double price = sprice == null ? 0.0 : Double.parseDouble(sprice);

        System.out.println("pid : " + pid);
        System.out.println("price : " + sprice);
        System.out.println("pname : " + pname);
        System.out.println("img : " + img);

        ProductForm pf = new ProductForm();

        pf.setImg(img);
        pf.setPname(pname);
        pf.setPrice(price);

        ProductValidate pv = new ProductValidate();

        List<String> errors = pv.validate(pf);

        try {
            if(errors != null && !errors.isEmpty()){
                request.setAttribute("errors", errors);
                return "/WEB-INF/view/index.jsp";
            }else{

                Product p = new Product();

                p.setPid(pid);
                p.setPname(pf.getPname());
                p.setImg(pf.getImg());
                p.setPrice(pf.getPrice());

                request.setAttribute("p", p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "/WEB-INF/view/product.jsp";
    }
}

到此我們自定義的MVC框架也就有了校驗(yàn)功能

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容