一个简单的MVC框架的实现-基于注解的实现
1、@Action注解声明
package com.togogo.webtoservice.annotations; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target(value=ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
// String namespace() default "";
}
2、@Path注解声明
package com.togogo.webtoservice.annotations; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* 如果放在类上面,表示名命空间
* 如果放在方法上面,表示路径
* @author Administrator
*
*/
@Target(value={ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Path { String value(); }
3、ActionExecute类
package com.togogo.webtoservice; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.togogo.webtoservice.annotations.Action;
import com.togogo.webtoservice.annotations.Path; /**
* 必须的问题 1、判断传进来的类的对象是不是一个Action 2、通过url,直接调用于Action的方法 3、返回转路径
*
* @author Administrator
*
*/
public class ActionExecute {
private Object action;
private Class<? extends Object> actionClass;
private HttpServletRequest request;
private HttpServletResponse response; ActionExecute(Object o, HttpServletRequest request,
HttpServletResponse response) {
this.action = o;
this.actionClass = this.action.getClass();
this.request = request;
this.response = response;
} /**
* 获得命名空间
*
* @return
*/
private String getNamespace() {
Path pathAnnotation = actionClass.getAnnotation(Path.class);
if (pathAnnotation != null) {
return pathAnnotation.value();
} else {
return null;
}
} /**
* 判断是否是一个Action
*
* @return
*/
private boolean isAction() {
Action actionAnnotation = actionClass.getAnnotation(Action.class);
if (actionAnnotation == null) {
return false;
} else {
return true;
}
} /**
* 获得方法
*
* @return
*/
private Method getMethod() {
String uri = request.getRequestURI(); Method[] methods = actionClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
Path path = m.getAnnotation(Path.class);
if (this.getNamespace() != null) {
if (uri.contains(this.getNamespace())) {
if (path != null) {
if (uri.contains(path.value())) {
return m;
}
}
}else{
System.out.println("--命名空间不匹配--");
return null;
} } else {
if (path != null) {
if (uri.contains(path.value())) {
return m;
}
}
}
}
return null;
} String execute() throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
if (isAction()) {
Method method = this.getMethod();
String rePath = (String) method.invoke(action, request, response);
return rePath;
} else {
System.out.println("--这不是一个Action--");
return null;
}
} }
4、核心控制器
package com.togogo.webtoservice; import java.io.IOException; 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 DispacherServlet extends HttpServlet {
private static String config=null;
private static String enconding="UTF-8"; @Override
public void init(ServletConfig config) throws ServletException {
String initConfig=config.getInitParameter("config");
String initEnconding=config.getInitParameter("enconding");
if(initConfig!=null){
DispacherServlet.config=initConfig;
}
//通过web描述符文件web.xml配置
if(initEnconding!=null){
DispacherServlet.enconding=initEnconding;
} super.init(config);
} /**
* 接收任何请求,
*/
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding(enconding);
response.setCharacterEncoding(enconding);
String uri = request.getRequestURI();
StringBuilder sb = new StringBuilder(uri);
String path = sb.substring(uri.lastIndexOf("/") + 1,
uri.lastIndexOf("!"));
System.out.println(path);
String className = Config.getClassName(path,config);
Object action = ActionFactory.create(className);
ActionExecute actionExecute =new ActionExecute(action,request, response);
String result = actionExecute.execute(); if (result.contains(":")) {
StringBuilder resultStr = new StringBuilder(result);
String rePath=resultStr.substring(result.indexOf(":")+1, result.length());
if(result.contains("redirect:")){
response.sendRedirect(rePath);
}else if(result.contains("forward:")){
request.getRequestDispatcher(rePath).forward(request, response);
} } else {
request.getRequestDispatcher(result).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} } }
5、Action对象工厂
package com.togogo.webtoservice; /**
* 一个创建Action的工厂
* @author Administrator
*
*/
public class ActionFactory { public static Object create(String className){
Object action=null;
try {
action = (Object)Class.forName(className).newInstance();
} catch (InstantiationException e) { e.printStackTrace();
} catch (IllegalAccessException e) { e.printStackTrace();
} catch (ClassNotFoundException e) { e.printStackTrace();
}
return action;
} }
6、配置文件类
package com.togogo.webtoservice; import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle; /**
* 路径与类名映身
*
* @author Administrator
*
*/
public class Config {
// private static Map<String, String> classNames = new HashMap<String,
// String>(); /**
* 通过key
*
* @param key
* @return
*/
public static String getClassName(String key, String config) {
ResourceBundle bundle = null;
if (config == null||"".equals(config)) {
bundle = ResourceBundle.getBundle("Action");
} else {
bundle = ResourceBundle.getBundle(config);
}
return bundle.getString(key);
} }
--------------------------------------------------------测试框架------------------------------------------------
7、UserAction类
package com.togogo.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.togogo.webtoservice.annotations.Action;
import com.togogo.webtoservice.annotations.Path; @Action
public class UserAction { /**
* 用户登录
*
* @param request
* @param response
* @return
*/
@Path(value="login.do")
public String login(HttpServletRequest request, HttpServletResponse response) {
System.out.println("我在登录");
System.out.println("我在登录.");
System.out.println("我在登录..");
System.out.println("我在登录.");
System.out.println("我在登录..");
System.out.println("我在登录.");
System.out.println("我在登录..");
System.out.println("我在------登录..");
System.out.println("我在------登录..");
System.out.println("我在------登录..");
System.out.println("我在------登录..");
return "main.jsp";
} /**
* 用户注册
*
* @param request
* @param response
* @return
*/
@Path(value="register.do")
public String register(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("我在注册");
return "forward:main.jsp";
} /**
* 用户注册
*
* @param request
* @param response
* @return
*/
public String undo(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("我在撤消");
return "redirect:main.jsp";
} }
8、映射配置文件Action.properties
user=com.togogo.action.UserAction
9、web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>web_mvc_webtoservice</display-name>
<!-- 这是一个核心控制器 -->
<servlet>
<servlet-name>dispacherServlet</servlet-name>
<servlet-class>com.togogo.webtoservice.DispacherServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>resources.Action</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>dispacherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
10、测试页面
<%@ 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>
<a></a>
<form action="${pageContext.request.contextPath }/user!login.do" method="post">
<!-- <input name="clasName" value="com.togogo.action.UserAction"> -->
<input type="submit"> </form>
</body>
</html>
源码下载:
http://files.cnblogs.com/files/zhuyuejiu/web_mvc_webtoservice_annotation.zip
一个简单的MVC框架的实现-基于注解的实现的更多相关文章
- 自己动手写一个简单的MVC框架(第一版)
一.MVC概念回顾 路由(Route).控制器(Controller).行为(Action).模型(Model).视图(View) 用一句简单地话来描述以上关键点: 路由(Route)就相当于一个公司 ...
- AsMVC:一个简单的MVC框架的Java实现
当初看了<从零开始写一个Java Web框架>,也跟着写了一遍,但当时学艺不精,真正进脑子里的并不是很多,作者将依赖注入框架和MVC框架写在一起也给我造成了不小的困扰.最近刚好看了一遍sp ...
- 自己动手写一个简单的MVC框架(第二版)
一.ASP.NET MVC核心机制回顾 在ASP.NET MVC中,最核心的当属“路由系统”,而路由系统的核心则源于一个强大的System.Web.Routing.dll组件. 在这个System.W ...
- 一个简单的MVC框架的实现
1.Action接口 package com.togogo.webtoservice; import javax.servlet.http.HttpServletRequest; import jav ...
- MVC框架浅析(基于PHP)
MVC框架浅析(基于PHP) MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑.数 ...
- [.NET] 一步步打造一个简单的 MVC 网站 - BooksStore(一)
一步步打造一个简单的 MVC 网站 - BooksStore(一) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore 简介 主 ...
- [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(一)
一步步打造一个简单的 MVC 电商网站 - BooksStore(一) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore &l ...
- [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) (转)
http://www.cnblogs.com/liqingwen/p/6640861.html 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) 本系列的 GitHub地址:ht ...
- PHP之简单实现MVC框架
PHP之简单实现MVC框架 1.概述 MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种 ...
随机推荐
- Max Sum of Max-K-sub-sequence hdu3415
Max Sum of Max-K-sub-sequence Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ...
- PHP常用字符串处理函数
(1)strlen(string) 返回字符串长度 (2)strpos(string,find,begin) 返回find字符串第一次出现的位置(从0开始) string:处理的字符串 find:想找 ...
- 移动端效果之Swiper
写在前面 最近在做移动端方面运用到了饿了么的vue前端组件库,因为不想单纯用组件而使用它,故想深入了解一下实现原理.后续将会继续研究一下其他的组件实现原理,有兴趣的可以关注下. 代码在这里:戳我 1. ...
- ubuntu mount u盘以及cp拷贝文件夹
如果是ubuntu桌面环境的话,不用mount,接入的U盘就可以直接被系统识别,访问起来非常方便,但如果没有桌面环境呢,比如在ubuntu server端,如何访问U盘呢? 第一步:查看U盘信息sud ...
- 为什么阿里的程序员那么帅?---原来他们都有"编码规约扫描"神器在手
为了迎接十九大的到来,帝都城这几天也是满城风雨,听说早高峰期地铁站的人都排到天桥上了,哎,这就是该死的北漂生活.但是无论怎样,我依然在北京向各位问好! 之前总结过俩篇关于阿里Java开发手册的编程规约 ...
- 为UWP应用开启回环访问权限
最近在项目中遇到UWP调用WCF的需求,考虑到UWP不能寄宿WCF服务(如果能,或者有类似技术,请告知),于是写了一个WPF程序寄宿WCF服务,然后再用UWP调用服务. 写的时候并没有碰到什么问题,直 ...
- javaScript 设计模式系列之四:组合模式
介绍 组合模式(Composite Pattern):组合多个对象形成树形结构以表示具有"整体-部分"关系的层次结构.组合模式对单个对象(即叶子对象)和组合对象(即容器对象)的使用 ...
- putty 的美化
1. 中文乱码问题. 这个问题由来已久,每当我查看 mount到linux下的windows 中文目录的时候,都是一堆乱码, putty 也拒绝我输入中文, 一句话,这玩意,对中文过敏. ...
- python中sys.exit()和os._exit(0)退出程序
python中退出程序的两种方法,0为默认状态,可以为空,两者均会退出当前运行的程序,os._exit(0)中的0不能省略 sys.exit(0):可以捕获SystemExit异常,然后做相应的清理工 ...
- javascript方法的方法名慎用close
通常我们在定义了与window同名的方法时,会自动覆盖掉window同名的方法.close()方法也不例外.示例: <!DOCTYPE html PUBLIC "-//W3C//DTD ...