这两天用jsp+servlet+MySQL开发了一个企业网站,后台和前台都有,功能已经实现了,现在总结发现,servlet是真的多,我这个系统有7个表,后台实现一遍增删改查,就得有28个servlet,而且还有前台的部分,servlet的数量真的太多了,想想看springmvc,其实是可以写一个轻量级的springmvc的。
在Servlet中实现类似Spring的@Controller注解功能,主要是通过自定义注解和一个中央处理器(如Servlet过滤器或一个集中的Servlet)来解析这些注解并将请求映射到相应的方法。下面是一个简单的示例:
- 自定义注解 -
Controller
和RequestMapping
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value();
}
- 自定义控制器类
@Controller
public class MyController {
@RequestMapping(value = "/hello")
public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().write("Hello, World!");
}
}
- 创建一个过滤器来处理请求映射
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class DispatcherFilter implements Filter {
private Map<String, Method> handlerMapping = new HashMap<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 扫描所有带有@Controller注解的类,并将它们注册到handlerMapping中
// 这里需要使用反射或类路径扫描库(如ClassGraph)
// 以下代码仅为示例,实际应用中需要根据项目结构进行调整
Class<MyController> clazz = MyController.class;
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping annotation = method.getAnnotation(RequestMapping.class);
handlerMapping.put(annotation.value(), method);
}
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String uri = request.getRequestURI();
Method method = handlerMapping.get(uri);
if (method != null) {
try {
method.invoke(method.getDeclaringClass().newInstance(), request, response);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
public void destroy() {
}
}
- 在web.xml中配置过滤器
<filter>
<filter-name>dispatcher</filter-name>
<filter-class>com.example.DispatcherFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>dispatcher</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
请注意,上述代码仅作为示例,实际应用中可能需要处理更多细节,如异常处理、类型安全、参数绑定等。此外,使用反射和类路径扫描可能会带来性能影响,因此在生产环境中应考虑优化。
标签:java,RequestMapping,springmvc,public,搞个,import,servlet,method,轻量级 From: https://blog.csdn.net/svygh123/article/details/139710314