SpringMVC处理请求的大致流程:
我们来开始着手手写一个SpringMVC框架。
新建一个springMVC项目,流程参见
SpringMVC框架搭建流程
引入servlet相关的jar包:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
新建一个servlet:
模拟springmvc,起名为LgDispatcherServlet
package com.lagou.edu.mvcframework.servlet;
import javax.servlet.http.HttpServlet;
/**
* @author liuyj
* @Title: LgDispatcherServlet
* @create 2020-06-11 14:22
* @ProjectName springmvc-demo
* @Description: TODO
*/
public class LgDispatcherServlet extends HttpServlet {
}
web.xml中注册我们新建的LgDispatcherServlet:
<servlet>
<servlet-name>lgmvc</servlet-name>
<servlet-class>com.lagou.edu.mvcframework.servlet.LgDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>lgmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
新建几个自定义注解:
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouAutowired {
String value() default "";
}
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouController {
String value() default "";
}
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouRequestMapping {
String value() default "";
}
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouService {
String value() default "";
}
新建demo包下的service及implement实现类及controller并加上相应的注解:
service:
package com.lagou.edu.demo.service;
public interface IDemoService {
String get(String name);
}
impl:
package com.lagou.edu.demo.service.impl;
import com.lagou.edu.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouService;
@LagouService("demoService")
public class DemoServiceImpl implements IDemoService {
@Override
public String get(String name) {
System.out.println("service 实现类中的name参数:" + name) ;
return name;
}
}
controller:
package com.lagou.edu.demo.controller;
import com.lagou.edu.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@LagouController
@LagouRequestMapping("/demo")
public class DemoController {
@LagouAutowired
private IDemoService demoService;
/**
* URL: /demo/query?name=lisi
* @param request
* @param response
* @param name
* @return
*/
@LagouRequestMapping("/query")
public String query(HttpServletRequest request, HttpServletResponse response,String name) {
return demoService.get(name);
}
}
本节到此结束。
下一节我们来开始结构开发设计。
欢迎访问:
微信公众号(程序员资料站):code_data