代码实现SpringMvc
偶然看到一篇100多行实现SpringMvc的博客,阅读后整理加实现出来。大家共勉!(纸上得来终觉浅,绝知此事要躬行。)
实现Spring的部分。
- Bean工厂,统一创建Bean;
- IOC,实现Bean的依赖注入;
- DispatchServlet,SpringMVC的路径映射。
代码解析如下:
1、首先创建Servelt,继承HttpServlet。覆盖init/doGet/doPost方法。
@Override
public void init() throws ServletException {
try {
// 初始化配置文件
initConfig(super.getServletConfig().getInitParameter(CONFIG_NAME));
// 扫描类
doScanPackage(configProperties.getProperty("packageScan"));
// 加载类
initBeanInitializing();
// 依赖注入
initBeanAutowired();
// 路径映射
initServletDispatch();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("====>beanFactory:\n"+beanFactory);
System.out.println("====>requestMap:\n"+requestMap);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
doDispatch(req,resp);
}
2、配置web.xml
<servlet>
<servlet-name>cwDispatchServlet</servlet-name>
<servlet-class>com.cw.servlets.CWDispatchServlet</servlet-class>
<init-param>
<param-name>dispatchConfig</param-name>
<param-value>config.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>cwDispatchServlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
2.1、配置文件config.properties在根目录,如下
# 设置配置文件
packageScan=com.cw.demo
3、定义支持的注入,如
Autowired
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
public @interface CWAutowired {
String value() default "";
}
Controller
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface CWController {
String value() default "";
}
RequestMapping
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@Inherited
public @interface CWRequestMapping {
String value() default "";
}
Service
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface CWService {
String value() default "";
}
4、在Servlet的init方法中,依次实现
4.1、加载配置文件
private void initConfig(String configName){
InputStream inputStream = null;
try {
System.out.println("------->configName:"+configName);
inputStream = this.getClass().getClassLoader().getResourceAsStream(configName);
configProperties.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.1、扫描所有Java类
/**
* 扫描类
* @Title: doScanPackage
* @param packagePath
* @return void
*/
private void doScanPackage(String packagePath) {
System.out.println("path:"+packagePath.replaceAll("\\.", "/"));
URL url = this.getClass().getClassLoader().getResource("/"+packagePath.replaceAll("\\.", "/"));
File file = new File(url.getFile());
for(File sub:file.listFiles()) {
if(sub.isDirectory()) {
doScanPackage(packagePath+"."+sub.getName());
}else {
String clsName = packagePath+"."+sub.getName().replace(".class","");
this.clsList.add(clsName);
}
}
}
4.3、初始化类
private void initBeanInitializing() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
for(String clsName:clsList) {
Class cls = Class.forName(clsName);
if(cls.isAnnotationPresent(CWController.class)) {
String name = cls.getSimpleName();
beanFactory.put(lowerFirstChar(name) , cls.newInstance());
}else if(cls.isAnnotationPresent(CWService.class)) {
CWService service = (CWService) cls.getAnnotation(CWService.class);
String defaultName = service.value();
if(!"".equals(defaultName)) {
beanFactory.put(defaultName, cls.newInstance());
}else {
Class[] interfaces = cls.getInterfaces();
Object instance = cls.newInstance();
for(Class inter:interfaces) {
beanFactory.put(lowerFirstChar(inter.getSimpleName()), instance);
}
}
}else if(cls.isAnnotationPresent(CWComponent.class)){
String name = cls.getName();
beanFactory.put(lowerFirstChar(name), cls.newInstance());
}
}
}
4.4、完成类的依赖注入
private void initBeanAutowired() throws IllegalArgumentException, IllegalAccessException {
for(Map.Entry<String, Object> entry:beanFactory.entrySet()) {
Object bean = entry.getValue();
Field[] fields = bean.getClass().getDeclaredFields();
if(null == fields || fields.length ==0 ) {
continue;
}
for(Field field:fields) {
if(field.isAnnotationPresent(CWAutowired.class)) {
String fieldTypeName = field.getType().getSimpleName();
field.setAccessible(true);
field.set(bean, beanFactory.get(this.lowerFirstChar(fieldTypeName)));
}
}
}
}
4.5、完成request的路径映射
private void initServletDispatch() {
for(Map.Entry<String, Object> entry:beanFactory.entrySet()) {
Object bean = entry.getValue();
System.out.println(entry.getKey()+":"+entry.getValue());
if(!bean.getClass().isAnnotationPresent(CWController.class)) {
continue;
}
// 基本路径
String basePath = "";
if(bean.getClass().isAnnotationPresent(CWRequestMapping.class)) {
basePath = ((CWRequestMapping)bean.getClass().getAnnotation(CWRequestMapping.class)).value();
}
System.out.println("=========>basePath:"+basePath);
// 方法路径
Method[] methods = bean.getClass().getMethods();
for(Method method:methods) {
if(method.isAnnotationPresent(CWRequestMapping.class)) {
String path = ((CWRequestMapping)method.getAnnotation(CWRequestMapping.class)).value();
requestMap.put(("/"+basePath +"/"+path).replaceAll("/+", "/"), method);
}
}
}
}
5、处理页面请求
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException {
String url = req.getRequestURI();
String contextPath = req.getContextPath();
url = url.replace(contextPath, "").replaceAll("/+", "/");
System.out.println("=========>request url:"+url);
Method method = this.requestMap.get(url);
if(null == method) {
resp.getOutputStream().write("404 not found!".getBytes("UTF-8"));
return;
}
String beanName = this.lowerFirstChar(method.getDeclaringClass().getSimpleName());
try {
method.invoke(beanFactory.get(beanName), req,resp);
}catch (Exception e) {
e.printStackTrace();
resp.getOutputStream().write("404 not found!".getBytes("UTF-8"));
}
}
6、添加测试类了
HelloWorldAction.java
@CWController
@CWRequestMapping("/h")
public class HelloWorldAction {
@CWAutowired
private IUserService userService; @CWRequestMapping("/hello.htm")
public void hello(HttpServletRequest request,HttpServletResponse response) {
try {
System.out.println(userService.getUserNameById(1L));
response.getWriter().write("hello World!");
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IUserService.java
public interface IUserService {
public String getUserNameById(Long id);
}
UserServiceImpl.java
@CWService
public class UserServiceImpl implements IUserService { @Override
public String getUserNameById(Long id) {
return "master";
} }
7、tomcat启动,大功告成
http:127.0.0.1:8080/h/hello.htm
总结:
1、看别人的代码,很简单,自己实现就发现很多坑。关键还是要自己实践。实践!实践!实践!
备注:
1、参考来源
https://www.toutiao.com/i6636629045259796995/
2、工程源码
https://pan.baidu.com/s/1F0el_nwDJ99-AYueeH0esw
代码实现SpringMvc的更多相关文章
- 基于java代码的springmvc配置
在我的印象中,开发一个web项目首选当然是springmvc,而配置springmvc无非就是web.xml里配置其核心控制器DispatcherServlet.然后把所有的请求都交给它处理,再配个视 ...
- 基于java代码的Spring-mvc框架配置
Spring 版本 4.3.2 maven项目 1.首先上项目目录图,主要用到的配置文件,略去css和js的文件 引包: 2.主要代码: (1)NetpageWebAppInitializer类 ...
- 编写手机端自适应页面案例,springMVC代码,SpringMVC上传代码,去掉input框中原有的样式,使ios按钮没有圆角,css中的border-radius类似
1.编写的页面 <%@ page language="java" contentType="text/html; charset=UTF-8" page ...
- SpringMVC(一) 简单代码编写,注解,重定向与转发
SpringMVC是什么 SpringMVC是目前最好的实现MVC设计模式的框架,是Spring框架的一个分支产品,以SpringIOC容器为基础,并利用容器的特性来简化它的配置.SpringMVC相 ...
- 零配置文件搭建SpringMVC实践纪录
本篇记录使用纯java代码搭建SpringMVC工程的实践,只是一个demo.再开始之前先热身下,给出SpringMVC调用流程图,讲解的是一个http request请求到达SpringMVC框架后 ...
- 3.SpringMVC修改配置文件路径和给界面传递数据
1.修改配置文件路径 达到 配置多文件的目的 web.xml文件中基础配置有springMVC配置的servlet路径 <servlet-name>SpringMVC</serv ...
- SpringMVC与Struts2配置区别
Spring MVC模型与Struts2模型应用: Html表单: 上述这两段代码无论是SpringMVC还是Struts2,都可以共用.而在请求响应处理类(也就是Controller)上的设计差 ...
- springmvc学习(二)——使用RequestMapper请求映射
本次内容是@RequestMapping,后面会有实例代码 Spring MVC 使用 @RequestMapping 注解为控制器指定可以处理哪些 URL 请求在控制器的类定义及方法定义处都可标注@ ...
- SpringMVC Ajax返回的请求json
的方式来解决在中国字符串乱码问题
1.org.springframework.http.converter.StringHttpMessageConverter类是类处理请求或相应的字符串.和默认字符集ISO-8859-1,所以当返回 ...
随机推荐
- “全栈2019”Java异常第三章:try代码块作用域详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...
- iOS中文本属性Attributes
NSFontAttributeName //设置字体大小 NSParagraphStyleAttributeName //设置段落格式 NSForegroundColorAttributeName / ...
- Vmware下Kali设置桥接网络无法上网
1.检查是否设置桥接 2.编辑>首选项>虚拟网络编辑器>选对本机上网的网卡 3.检查上网的网卡>适配器属性栏有没有 Vmware Bridge Protocol 桥接的服务. ...
- declare命令
还是围绕以下几个问题进行学习; 1.declare是什么? 2.问什么要用declare? 3.怎样使用declare? 1.declare是什么? ♦declare应用的很多,向我们各种语言都会有声 ...
- P3292 [SCOI2016]幸运数字
题目链接 题意分析 一句话题意 : 树上一条链中挑选出某些数 异或和最大 我们可以考虑维护一个树上倍增线性基 然后倍增的时候 维护一个线性基合并就可以了 写起来还是比较容易的 CODE: #inclu ...
- leetcode-91-解码方法(动态规划和递归两种解法)
题目描述: 一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数 ...
- ownCloud问题处理server replied 423 Locked to
打开owncloud 数据库备份:oc_file_locks表(备份免错哦)然后清空该表,客户端同步一次,故障解决 owncloud大的数据无法同步..
- Bootstrap-datepicker日期时间选择器的简单使用
日期时间选择器 目前,bootstrap有两种日历.datepicker和datetimepicker,后者是前者的拓展. Bootstrap日期和时间组件: 使用示例: 从左到右依次是十年视图.年视 ...
- Drupal V7.3.1 框架处理不当导致SQL注入
这个漏洞本是2014年时候被人发现的,本着学习的目的,我来做个详细的分析.漏洞虽然很早了,新版的Drupal甚至已经改变了框架的组织方式.但是丝毫不影响对于漏洞的分析.这是一个经典的使用PDO,但是处 ...
- Access network
1 State transfering A•Mobility:开机-搜寻PLMN/CELL来发现自己在网络中的位置•Attach request•Auth request•Auth res ...