servlet+Java反射機制實現mvc模式

來源:互聯網
上載者:User

標籤:ast   direct   名稱   exce   exception   list   color   servlet   htm   

一,servlet基類,BaseController類繼承HttpServlet,實現了doGET和doPost方法,相當於springmvc的dispacterservlet,我們只需要在web.xml註冊一個BaseController即可。BaseController.avapackage com.easygo.controller;import java.io.IOException;import java.util.Properties;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BaseController extends HttpServlet {        /**     *      */    private static final long serialVersionUID = 1L;    //調用properties 設定檔    private  Properties  properties=new Properties();    //字元編碼集合    private String charset="utf-8";        @Override    public void init(ServletConfig config) throws ServletException {                  //擷取初始化的  參數  key  value     String  configname=config.getInitParameter("configname");        try {        //自動載入設定檔        properties.load(this.getClass().getClassLoader().getResourceAsStream(configname));                  //通過設定檔擷取到字元編碼集      String tmp=    properties.getProperty("charset");        if(tmp!=null){            charset=tmp;        }            } catch (IOException e) {            e.printStackTrace();            System.out.println("讀取失敗!");        }        }            @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {    try {        //設定字元編碼集        req.setCharacterEncoding(charset);            resp.setCharacterEncoding(charset);                    //擷取到  uri        String act=      req.getRequestURI();        // System.out.println(act);        //      /MVCController/  user .do           // user  --- 找到Config檔案的com.uplooking.action.UserAction        act=act.substring(act.lastIndexOf("/")+1,act.lastIndexOf(".do"));        // 擷取類路徑  System.out.println(act);         String classPath= properties.getProperty(act);        // System.out.println(classPath);                if(classPath==null||classPath.equals("")){            resp.setContentType("text/html");            resp.getWriter().println("沒有您要訪問的路徑!");            return;        }                        //進行反射調用           Class    iActionClass =Class.forName(classPath);                //反向執行個體        IAction   iAction=(IAction) iActionClass.newInstance();                //交給 子方法進行處理    處理完之後  只要 返回   String  request response        //封裝傳回值         String result= iAction.execute(req, resp);        System.out.println("傳回值="+result);                //有傳回值的時候        if(result!=null&&!"".equals(result)){              /*        1 預設轉寄    return  "index.jsp";              2 重新導向        return  "@red_index.jsp"               3json   return  "@json_{XXXXXX}"*/            if(result.contains("@red_")){                //重新導向                resp.sendRedirect(result.split("_")[1]);            }else if(result.contains("@json_")){                resp.setContentType("text/html");                resp.getWriter().println(result.split("_")[1]);                resp.getWriter().close();            }else{                req.getRequestDispatcher(result).forward(req, resp);            }                                    }else{            //沒有傳回值的時候            resp.setContentType("text/html");            resp.getWriter().println("沒有傳回值!");            return;        }                        } catch (ClassNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();        } catch (InstantiationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IllegalAccessException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }              }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doGet(req, resp);    }        }---------------------------------------------------------------------------------------------------------------------------------web.xml配置:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  <display-name>MVCController</display-name>      <servlet>         <servlet-name>BaseController</servlet-name>           <servlet-class>com.easygo.controller.BaseController</servlet-class>         <init-param>            <param-name>configname</param-name>            <param-value>ActionConfig.properties</param-value>         </init-param>         <load-on-startup>0</load-on-startup>  </servlet>    <servlet-mapping>     <servlet-name>BaseController</servlet-name>     <url-pattern>*.do</url-pattern>  </servlet-mapping>        <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app> ---------------------------------------------------------------------------------------------------------------------------------IAction介面,Action類實現IAction介面package com.easygo.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.easygo.controller.IAction;public class BookAction implements IAction{    @Override    public String execute(HttpServletRequest req, HttpServletResponse resp) {                System.out.println("BookAction");        return "@red_index.jsp";    }} ---------------------------------------------------------------------------------------------------------------------------------ActionConfig.properties,key代表URL請求的名稱,以.do為尾碼,value是改類的全類名,用於反射。charset=utf-8#user.douser=com.easygo.action.UserAction#book.dobook=com.easygo.action.BookActionjson=com.easygo.action.JsonAction ---------------------------------------------------------------------------------------------------------------------------------UserAction.java類,原理與springMVC的RequestMapping註解下的方法一樣,用於資料返回和頁面跳轉。package com.easygo.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.easygo.controller.IAction;public class UserAction  implements IAction {    @Override    public String execute(HttpServletRequest req, HttpServletResponse resp) {        System.out.println("UserAction");        return "index.jsp";    }        /* *   BaseController.java  把  HttpServletRequest req, HttpServletResponse resp *   通過反射 交給指定的類的 方法去處理  *    *             | *              | *    *          處理邏輯方法 *    *   處理完之後        轉寄 *            重新導向 *            json *             *      String   X指向   _   訪問的頁面/資料     *             | *             | *             | *      這個String --BaseController    *    *     @Override    public String execute(HttpServletRequest req, HttpServletResponse resp) {        // TODO Auto-generated method stub        return null;    }        */} ---------------------------------------------------------------------------------------------------------------------------------JsonAction.java用於json資料的返回。package com.easygo.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.easygo.controller.IAction;public class JsonAction implements IAction{    @Override    public String execute(HttpServletRequest req, HttpServletResponse resp) {                System.out.println("JsonAction");        return "@json_{asdsadsadsadsadad}";    }} ---------------------------------------------------------------------------------------------------------------------------------index.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body>               index.jsp                   </body></html> ---------------------------------------------------------------------------------------------------------------------------------indexX.jsp<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><a href="user.do">user.do</a></body></html> ---------------------------------------------------------------------------------------------------------------------------------測試:運行indexX.jsp(tomcat8.0)點擊:user.do直接跳轉到index.jspURL:http://localhost:8088/MVCController/user.do具體代碼:連結: https://pan.baidu.com/s/1spMCZ0hAn_FLAZb1OG5-Pw 密碼: 77zi

 

servlet+Java反射機制實現mvc模式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.