<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 閱讀(1009) 評論(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

    生活保健

    解析文件

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 亚洲精品免费观看| 狠狠久久永久免费观看| 亚洲国产情侣一区二区三区| 曰批全过程免费视频在线观看| 亚洲爆乳AAA无码专区| 中文字幕精品亚洲无线码二区| 97在线视频免费| 亚洲高清毛片一区二区| 中文字幕亚洲综合久久男男| 91热久久免费精品99| 亚洲av无码一区二区三区人妖| 亚洲中文字幕无码永久在线| 歪歪漫画在线观看官网免费阅读| 一级毛片正片免费视频手机看 | 亚洲女同成人AⅤ人片在线观看| 国产日韩AV免费无码一区二区| 亚洲一区精品视频在线| 亚洲毛片不卡av在线播放一区| 8x8×在线永久免费视频| 美女被暴羞羞免费视频| 亚洲国产精品lv| 亚洲成av人在片观看| 曰曰鲁夜夜免费播放视频| 一级毛片a免费播放王色电影 | 久久综合久久综合亚洲| 亚洲日韩v无码中文字幕| 麻豆国产人免费人成免费视频| 久热免费在线视频| 日韩电影免费在线观看网址| 亚洲一区无码中文字幕乱码| 亚洲精品乱码久久久久久中文字幕 | 亚洲AV无码成人网站在线观看| 亚洲AV永久精品爱情岛论坛| 四虎在线播放免费永久视频| 国产在线观看麻豆91精品免费 | 美女视频黄的全免费视频| 一区二区三区在线免费| 亚洲美国产亚洲AV| 亚洲欧洲久久精品| 久久亚洲精品中文字幕无码| 亚洲午夜无码片在线观看影院猛|