<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    web.xml中servlet控制參數方法

    web.xml中servlet:

        <servlet>   <!--接著順序加載servlet被初始化-->
               
    <!-- servlet獲得控制文件Class的名字,類名 -->
            
    <servlet-name>smvcCoreDispatcher</servlet-name>
            
    <servlet-class>org.bluechant.mvc.core.CoreDispatcherController</servlet-class>
            
    <init-param>
                
    <param-name>templateLoaderPath</param-name>
                
    <param-value>/WEB-INF/view</param-value>
            
    </init-param>
            
    <init-param>
                
    <param-name>defaultEncoding</param-name>
                
    <param-value>GBK</param-value>
            
    </init-param>
            
    <init-param>
                
    <param-name>contextConfigLocation</param-name>
                
    <param-value>/WEB-INF/smvc_config/smvc-config.xml</param-value>
            
    </init-param>
            
    <load-on-startup>1</load-on-startup><!-- 加載路徑 -->
        
         
    </servlet>
        
    <servlet-mapping>
            
    <servlet-name>smvcCoreDispatcher</servlet-name>
            
    <url-pattern>*.do</url-pattern>
        
    </servlet-mapping>
        
        
    <welcome-file-list>
            
    <welcome-file>login.html</welcome-file>
        
    </welcome-file-list>

    web.xml對應的servlet控制java改寫:

    package org.bluechant.mvc.core;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Method;
    import java.util.Enumeration;
    import java.util.Locale;
    import java.util.Map;

    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.log4j.Logger;
    import org.bluechant.mvc.controller.ModelAndView;
    import org.bluechant.mvc.core.util.ServletUtils;

    import freemarker.template.Configuration;
    import freemarker.template.ObjectWrapper;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    import freemarker.template.TemplateExceptionHandler;

    public class CoreDispatcherController extends HttpServlet {
        
        private Logger logger = Logger.getLogger(CoreDispatcherController.class);
        
        private CacheManager cache ;
        
        private String baseControllerClass = "org.bluechant.mvc.controller.Controller";

        private static final long serialVersionUID = 1L;
        
        private Configuration cfg ;
        
        private String templateLoaderPath ;
        
        private String defaultEncoding ;    
        
        private String contentType ;

        private String contextConfigLocation ;
        
        private ActionConfig actionCoinfig ;    
        
        public void init(ServletConfig config) throws ServletException {
            
            super.init(config);
            //super.init(config);

            String absPath = config.getServletContext().getRealPath("/");//獲得系統絕對路徑
            System.out.println("absPath:"+absPath);
            //getRealPath("/virtual_dir/file2.txt")應該返回"C:\site\a_virtual\file2.txt"   getRealPath("/file3.txt")應該返回null,因為這個文件不存在。 
            ///返回路徑D:\Java\workspaces\helios\newshpt\獲得文件路徑
            defaultEncoding = getInitParameter("defaultEncoding");
            
            templateLoaderPath = getInitParameter("templateLoaderPath");
            //");//從web.xml中獲得templateLoaderPath信息,web.xml中對應的路徑”/WEB-INF/view“
            
            contextConfigLocation = getInitParameter("contextConfigLocation");
            System.out.println("contextConfigLocation:"+contextConfigLocation);
            ///獲得web.xml文件中路徑WEB-INF/smvc_config/smvc-config.xml
            actionCoinfig = new ActionConfig();
            actionCoinfig.load(absPath+contextConfigLocation);//文檔進行解析與讀取,
            ///D:\Java\workspaces\helios\newshpt\WEB-INF/smvc_config/smvc-config.xml
            contentType = "text/html;charset="+defaultEncoding ;
            
            //創建Configuration實例,Configuration是入口,通過它來獲得配置文件
            cfg = new Configuration();
            //設置模板路徑, getServletContext(),所有是所有路徑都能拿到的..
            cfg.setServletContextForTemplateLoading(getServletContext(), templateLoaderPath);
            //cfg.setServletContextForTemplateLoading(arg0, arg1)
            //設置編碼格式
            cfg.setEncoding(Locale.getDefault(), defaultEncoding);
            
            //init cache manager
            cache = CacheManager.getInstance();
        }
        
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            processRequest(request,response);
        }
        
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
            processRequest(request,response);
            
        }
        
        private void showRequestParams(HttpServletRequest request){
            Enumeration en = request.getParameterNames();
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        //map.put(paramName, paramValue);
                        //System.out.println(paramName+"\t"+paramValue);
                    }
                }else if(paramValues.length >1 ){//checkbox
                    //map.put(paramName, paramValues);
                    //System.out.println(paramName+"\t"+paramValues);
                }
            }
        }
        
        public void processRequest(HttpServletRequest request, HttpServletResponse response){
            
            try {
                request.setCharacterEncoding(defaultEncoding);
                showRequestParams(request);//waiting back to resolve
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } // set request encoding
            
            ModelAndView mv = analyzeRequest(request);        
            try {
                invokeActionHandler(mv,request);
                if(mv.getViewPath().endsWith(".ftl")){
                    invokeViewResolverHandler(mv , response , request);
                }else{
                    response.sendRedirect(mv.getWebroot()+mv.getViewPath());
                }    
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
        
        public ModelAndView analyzeRequest(HttpServletRequest request){        
            ModelAndView modelAndView = new ModelAndView();            
            logger.debug("request url path is : "+request.getRequestURI());
            String requestPath = request.getRequestURI(); // /newshpt/account!login.do
            String webroot = request.getContextPath() ; // /newshpt
            System.out.println("request url path is : "+requestPath);
            System.out.println("request webroot path is : "+webroot);
            modelAndView.setWebroot(webroot);
            String actionFullName = requestPath.substring(webroot.length()); // /account!login.do
            System.out.println("actionFullName : "+actionFullName);
            String[] temp = actionFullName.split("!");
            String method = "execute";
            if(temp.length==2){
                 method = temp[1].split("\\.")[0];
            }
            System.out.println("method : "+method);
            String actionName = temp[0]; // /demo
            System.out.println("actionName : "+actionName);
            String className = actionCoinfig.getClassName(actionName);
            System.out.println("className :"+className);
            modelAndView.setClassName(className);
            modelAndView.setMethodName(method);
            modelAndView.setAction(actionName);
            
            return modelAndView ;
        }
        
        /**
         * invoke the request controller's target method 
         * param ModelAndView will be mofified during the process
         * @param mv
         * @param request
         * @throws Exception 
         */
        public void invokeActionHandler(ModelAndView mv , HttpServletRequest request) throws Exception{
            String className = mv.getClassName();
            String methodName = mv.getMethodName();
            //load class
            Class controllerClass = cache.loadClass(className);
            Class parentControllerClass = cache.loadClass(baseControllerClass);
            //load method
            Method setRequest = cache.loadMethod(parentControllerClass, "setRequest", new Class[] { HttpServletRequest.class });    
            Method setModelAndView = cache.loadMethod(parentControllerClass, "setModelAndView", new Class[] { ModelAndView.class });//org.bluechant.mvc.controller.Controller-setModelAndView@6024418  public void org.bluechant.mvc.controller.Controller.setModelAndView(org.bluechant.mvc.controller.ModelAndView)
            Method targetMethod = cache.loadMethod(controllerClass, methodName, new Class[]{});
            //buiid controller instance and invoke target method
            Object instance = controllerClass.newInstance();
            setRequest.invoke(instance, new Object[] { request });//對帶有指定參數的指定對象調用由此 Method 對象表示的基礎方法    
            setModelAndView.invoke(instance, new Object[] { mv });
            targetMethod.invoke(instance, new Object[]{});        
        }
        
        /**
         * send data to view model , and generate the view page by FreeMarker
         */
        public void invokeViewResolverHandler(ModelAndView modelAndView , HttpServletResponse response ,HttpServletRequest request){    
            //convert session attributes to sessionModel , and push to modelAndView
            Map sessionModel = ServletUtils.sessionAttributesToMap(request.getSession());// userSources=[/admin, /button/custom, /custom, /delivery, /loadShip, /unloadPickUp, /unloadShip]
            modelAndView.put("Session", sessionModel);
            response.setContentType(contentType); 
            try {//初始化FreeMarker
                PrintWriter out = response.getWriter();
                Template template = cfg.getTemplate(modelAndView.getViewPath());//取得生成模版文件
                template.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);//setTemplateExceptionHandler
                //set the object wrapper , beanwrapper is the perfect useful objectWrapper instance
                template.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);// 設置對象包裝器
                template.process(modelAndView, out);//模版環境開始載入..
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        }
        
    }


    smvc-config.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <smvc-config>    
        
    <action name="/account" class="com.cenin.tjport.shpt.mvc.controller.AccountController"/>
        
    <action name="/yard" class="com.cenin.tjport.shpt.mvc.controller.DuiCunController"/>
    </smvc-config>



     

    posted on 2012-05-22 15:08 youngturk 閱讀(1008) 評論(0)  編輯  收藏 所屬分類: servletweb.xml解析

    <2012年5月>
    293012345
    6789101112
    13141516171819
    20212223242526
    272829303112
    3456789

    導航

    統計

    公告

    this year :
    1 jQuery
    2 freemarker
    3 框架結構
    4 口語英語

    常用鏈接

    留言簿(6)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    相冊

    EJB學習

    Flex學習

    learn English

    oracle

    spring MVC web service

    SQL

    Struts

    生活保健

    解析文件

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 久久久久久亚洲精品中文字幕| 国产免费午夜a无码v视频| 亚洲一区无码中文字幕| 四虎国产精品成人免费久久 | 免费少妇a级毛片人成网| 亚洲日韩精品无码专区加勒比☆| 1000部拍拍拍18免费网站| 亚洲美女色在线欧洲美女| 91大神在线免费观看| 亚洲欧洲日产专区| 国产啪精品视频网免费| 亚洲xxxx视频| 免费在线观看污网站| 日本精品久久久久久久久免费| 亚洲人成网站18禁止一区| aa毛片免费全部播放完整| 国产亚洲成av片在线观看| 99re在线这里只有精品免费| 亚洲精品偷拍无码不卡av| 在线观看无码AV网站永久免费| 亚洲熟女乱色一区二区三区 | 亚洲欧洲国产精品香蕉网| 日本三级在线观看免费| 亚洲视屏在线观看| 中文字幕无码免费久久99| 亚洲av成人一区二区三区观看在线| 俄罗斯极品美女毛片免费播放| 久久成人永久免费播放| 91亚洲精品视频| 成人毛片免费观看视频在线| 黄页网站在线视频免费| 亚洲AV无码不卡在线播放| 亚洲人成网站免费播放| 特级做a爰片毛片免费看| 亚洲色四在线视频观看| 国产一级一片免费播放i| 免费无码av片在线观看| 亚洲综合在线一区二区三区| 日本亚洲国产一区二区三区| **一级一级毛片免费观看| 免费亚洲视频在线观看|