MFC编程实例:从零实现MVC框架之控制层(6)
小职 2018-07-05 来源 : 阅读 1245 评论 0

摘要:本文主要向大家介绍了MFC编程实例:从零实现MVC框架之控制层(6),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

本文主要向大家介绍了MFC编程实例:从零实现MVC框架之控制层(6),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

最早使用的控制层框架就是struts1 然后是struts2 在之后就是SpringMVC的Controller了。就个人而言感觉Spring的Controller使用
很方便也很简单。所以我们的控制层就模仿Spring的Controller来实现。包括注解、返回页面的方式、以及之后的文件上传都依稀能看到
SpringMVC的身影。并且我们也是用Servlet来实现,真是一个精简版的Spring Controller,哈....

注解

[java] view plain copy

1. package com.hc.web.annotation;  

2.   

3. import java.lang.annotation.ElementType;  

4. import java.lang.annotation.Retention;  

5. import java.lang.annotation.RetentionPolicy;  

6. import java.lang.annotation.Target;  

7.   

8. @Retention(RetentionPolicy.RUNTIME)  

9. @Target({ElementType.TYPE})  

10. public @interface Controller {  

11.   

12.     public String path();  

13. }  


 

[java] view plain copy

1. package com.hc.web.annotation;  

2.   

3. import java.lang.annotation.ElementType;  

4. import java.lang.annotation.Retention;  

5. import java.lang.annotation.RetentionPolicy;  

6. import java.lang.annotation.Target;  

7.   

8. @Retention(RetentionPolicy.RUNTIME)  

9. @Target({ElementType.METHOD})  

10. public @interface MethodMapping {  

11.   

12.     public String method();  

13. }  


控制器类信息

[java] view plain copy

1. package com.hc.web;  

2.   

3. import java.lang.reflect.Method;  

4. import java.util.Map;  

5.   

6. public class ControllerClassInfo {  

7.   

8.     private Class<?> cls;  

9.     private String path;  

10.     private Map<String,Method> methodMap;  

11.       

12.     public Class<?> getCls() {  

13.         return cls;  

14.     }  

15.     public void setCls(Class<?> cls) {  

16.         this.cls = cls;  

17.     }  

18.     public String getPath() {  

19.         return path;  

20.     }  

21.     public void setPath(String path) {  

22.         this.path = path;  

23.     }  

24.     public Map<String, Method> getMethodMap() {  

25.         return methodMap;  

26.     }  

27.     public void setMethodMap(Map<String, Method> methodMap) {  

28.         this.methodMap = methodMap;  

29.     }  

30.       

31.       

32.       

33. }  


控制器缓存

[java] view plain copy

1. package com.hc.web;  

2.   

3. import java.io.File;  

4. import java.lang.reflect.Method;  

5. import java.util.ArrayList;  

6. import java.util.HashMap;  

7. import java.util.List;  

8. import java.util.Map;  

9. import java.util.concurrent.ConcurrentHashMap;  

10.   

11. import com.hc.web.annotation.Controller;  

12. import com.hc.web.annotation.MethodMapping;  

13. /** 

14.  * 控制器缓存 

15.  * @author chuer 

16.  * @date 2014-7-16 下午3:54:57 

17.  * @version V1.0 

18.  */  

19. public class ControllerCache {  

20.   

21.     /*key: path   value: ControllerClassInfo*/  

22.     private static ConcurrentHashMap<String, ControllerClassInfo> cache = new ConcurrentHashMap<>();  

23.     public static final String PAKAGE = "com";//扫描的包名 根据自己的包名进行修改  

24.     public static final String PAKAGE_SOURCE = "/com/hc";//扫描的包名 根据自己的包名进行修改  

25.     public static final String SECOND_PAKAGE = "com.hc";//扫描的包名 根据自己的包名进行修改  

26.     static{  

27.         init();  

28.     }  

29.       

30.     private static void init(){  

31.         String path = ControllerCache.class.getResource(PAKAGE_SOURCE).getPath();  

32.         List<String> classes = new ArrayList<String>();  

33.         getAllClasses(new File(path),classes);  

34.         for(String p : classes){  

35.                 try{  

36.                     Class<?> cls = Class.forName(p);  

37.                     if(cls.isAnnotationPresent(Controller.class)){  

38.                         Controller ca = cls.getAnnotation(Controller.class);  

39.                         if(cache.containsKey(ca.path())){  

40.                             throw new Exception("duplicate Controller path:"+ca.path());  

41.                         }  

42.                         ControllerClassInfo cci = new ControllerClassInfo();  

43.                         cci.setCls(cls);  

44.                         cci.setPath(ca.path());  

45.                           

46.                         Method[] declaredMethods = cls.getDeclaredMethods();  

47.                         Map<String,Method> map = new HashMap<>();  

48.                         for(Method method : declaredMethods){  

49.                             if(method.isAnnotationPresent(MethodMapping.class)){  

50.                                 MethodMapping mm = method.getAnnotation(MethodMapping.class);  

51.                                 if(map.containsKey(mm.method())){  

52.                                     throw new Exception("duplicate Method name:"+mm.method());  

53.                                 }  

54.                                 map.put(mm.method(), method);  

55.                             }  

56.                         }  

57.                         cci.setMethodMap(map);  

58.                         cache.put(ca.path(), cci);  

59.                     }  

60.                 }catch(Exception e){  

61.                     e.printStackTrace();  

62.                 }  

63.         }  

64.     }  

65.       

66.     private static void getAllClasses(File file,List<String> files){  

67.         if(file.isDirectory()){  

68.             File[] listFiles = file.listFiles();  

69.             for(File f : listFiles){  

70.                 getAllClasses(f,files);  

71.             }  

72.         }else{  

73.             if(file.getAbsolutePath().endsWith(".class")){  

74.                 String substring = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(PAKAGE));  

75.                 substring = substring.substring(0, substring.lastIndexOf('.'));  

76.                 if(substring.contains("/")){  

77.                     substring = substring.replaceAll("/", ".");  

78.                 }else{  

79.                     substring = substring.replaceAll("\\\\", ".");  

80.                 }  

81.                 if(substring.contains(SECOND_PAKAGE)){  

82.                     files.add(substring);  

83.                 }  

84.             }  

85.         }  

86.     }  

87.       

88.     public static ControllerClassInfo get(String key){  

89.         return cache.get(key);  

90.     }  

91.       

92.     public static void main(String...args){  

93.           

94.     }  

95.       

96. }  


返回页面类

[java] view plain copy

1. package com.hc.web;  

2.   

3. public class View {  

4.   

5.     private String path;  

6.   

7.     public View(String path){  

8.         this.path = path;  

9.     }  

10.       

11.     public String getPath() {  

12.         return path;  

13.     }  

14.   

15.     public void setPath(String path) {  

16.         this.path = path;  

17.     }  

18.       

19.       

20. }  


控制器核心类

[java] view plain copy

1. package com.hc.web;  

2.   

3. import java.io.IOException;  

4. import java.lang.reflect.Method;  

5.   

6. import javax.servlet.ServletException;  

7. import javax.servlet.annotation.WebServlet;  

8. import javax.servlet.http.HttpServlet;  

9. import javax.servlet.http.HttpServletRequest;  

10. import javax.servlet.http.HttpServletResponse;  

11.   

12. import org.apache.commons.fileupload.servlet.ServletFileUpload;  

13.   

14. import com.hc.pool.DBPool;  

15. import com.hc.web.io.MutipartFile;  

16. import com.hc.web.io.UploadFileParse;  

17.   

18. /** 

19.  *  

20.  * @author chuer 

21.  * @date 2014-7-16 下午3:55:23 

22.  * @version V1.0 

23.  */  

24. @WebServlet(urlPatterns={"*.hc"},loadOnStartup=1)  

25. public class AbstractHcAction extends HttpServlet {  

26.     private static final long serialVersionUID = 1L;  

27.     @Override  

28.     public void init() throws ServletException {  

29.         DBPool.getInstance();  

30.     }  

31.   

32.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

33.         doPost(request,response);  

34.     }  

35.   

36.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

37.         request.setCharacterEncoding("utf-8");  

38.         String methodParam = request.getParameter("method");  

39.         String servletPath = request.getServletPath();  

40.         ControllerClassInfo controllerClassInfo = ControllerCache.get(servletPath);  

41.         try {  

42.             Class<?> cls = controllerClassInfo.getCls();  

43.             Object newInstance = cls.getConstructor(new Class[]{}).newInstance(new Object[]{});  

44.                           

45.             //调用controller方法  

46.             Method method = controllerClassInfo.getMethodMap().get(methodParam);  

47.             Object invoke = method.invoke(newInstance, request,response);  

48.             if(invoke != null && invoke instanceof View){  

49.                 View view = (View)invoke;  

50.                 request.getRequestDispatcher(view.getPath()).forward(request, response);  

51.             }  

52.         } catch (Exception e) {  

53.             e.printStackTrace();  

54.         }   

55.           

56.     }  

57.   

58. }  


具体控制器类

[java] view plain copy

1. package com.hc.sample.controller;  

2.   

3. import java.io.File;  

4. import java.sql.SQLException;  

5.   

6. import javax.servlet.http.HttpServletRequest;  

7. import javax.servlet.http.HttpServletResponse;  

8.   

9. import com.hc.annotation.Inject;  

10. import com.hc.sample.service.UserService;  

11. import com.hc.web.View;  

12. import com.hc.web.annotation.Controller;  

13. import com.hc.web.annotation.MethodMapping;  

14. import com.hc.web.io.MutipartFile;  

15.   

16. @Controller(path="/user.hc")      

17. public class UserController {  

18.   

19.     private UserService userService = TransactionProxyCache.cache.get(UserServiceImpl.class);  

20.       

21.     @MethodMapping(method="addUser")  

22.     public View addUser(HttpServletRequest request, HttpServletResponse response) throws SQLException{  

23.         userService.add();  

24.         return new View("user.jsp");  

25.     }  

26.       

27.     public void setUserService(UserService userService) {  

28.         this.userService = userService;  

29.     }  

30.       

31.       

32.   

33. }  


测试

把我们这个项目整体部署到tomcat下,因为我们使用WebServlet注解,所以用不着web.xml文件。
然后启动tomcat。再浏览器输入://localhost:8080/上下文/user.hc?method=addUser.

查看数据库和页面的变化。对了 webRoot下还得有一个user.jsp。也可以把WebServlet的注解去掉,然后把AbstractHcAction这个servlet配置到web.xml中。效果是一样的。

控制器就完成了, 下面的一章我们做IOC注入。

本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言VC/MFC频道!

本文由 @小职 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程