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

一,servlet基類,BaseController類繼承HttpServlet,實現了doGET和doPost方法,至關於springmvc的dispacterservlet,咱們只須要在web.xml註冊一個BaseController便可。 BaseController.ava package 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.do user=com.easygo.action.UserAction #book.do book=com.easygo.action.BookAction json=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.jsp URL:http://localhost:8088/MVCController/user.do
具體代碼:連接: https://pan.baidu.com/s/1spMCZ0hAn_FLAZb1OG5-Pw 密碼: 77zi
相關文章
相關標籤/搜索