对于刚入门JavaWeb开发的同学来说,都是从servlet和JSP开始学习的,在构建项目的过程中可能会使用mvc模型来搭建项目,但是在使用传统的web编程模型时,自己搭建一个较大型的项目时,总是会遇到一些问题:
- 一个请求对应一个servlet,导致servlet过多时,web.xml文件特别大,维护麻烦
- 即使采用根据请求参数method在servlet里派发的方式,这样可以减少servlet的个数,但这种方式也要求在每个servlet中写上很多重复的if…else…来进行请求方法的判断
- Servlet的映射地址写在web.xml文件中,工程较大时,如果映射地址发生修改,修改起来特别麻烦
更为重要的是,servlet调用由web服务器负责,开发人员想控制servlet的调度,以加入一些类似于权限控制的功能特别困难
这是传统web编程项目的难点,所以后来也出现了许多的开源web mvc框架,像springmvc和struts等框架,这些框架使用起来非常方便,所以现在基本上都是才有springmvc,ssh,ssm等框架来直接进行web项目开发的。
其实,在学习这些框架的过程中,更重要的是去学习这些框架的设计思想。下面,让我们自己动手来写一个简单的web框架的前置控制器吧。
需要用到的技术,不熟悉的同学可以先去了解一下相关的概念和用法。
Java反射机制
类加载机制
Annotation 注解
我们这个简单的web框架的前置控制器将具有一下的功能:
- 由一个中央控制器ControllerServlet处理所有的请求,并根据请求uri,派发不同的action进行处理
- 全注解配置,处理请求的action由注解配置其映射地址
- 支持method请求参数,根据客户机带来的method,调用action的相应方法进行处理,以减少action的数量
- 自动扫描类路径,并通过自定义类装载器加载所有处理请求的action,并关联到相应的处理uri上
例如,对于这个urihttp://localhost:8080/framework/test.do?method=login
,这个请求是*.do请求,我们把他转发ControllerServlet进行处理,ControllerServlet首先截取项目的/test,找到需要调用的action,再根据method=login来调用login方法进行处理。
下面开始我们项目的构建:
1. 新建一个web项目webFrameWork
2. 新建一个核心控制servlet,ControllerServlet,并在web.xml中进行相应的配置
ControllerServlet作为这个项目的核心控制器,需要完成的功能主要包括:
(1)项目运行时加载整个项目的action类
(2)解析用户的请求并执行相应的action
web.xml 配置文件如下:/webFrameWork/WebRoot/WEB-INF/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>webFrameWork</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>com.chen.ControllerServlet</servlet-class>
<!-- 每一次项目运行时加载这个servlet,(实例化并调用其init()方法) -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<!-- 配置映射url,过滤所有的*.do的请求 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
3. 实现Action注解
我们的框架需要实现的Action类应该是这样的
/webFrameWork/src/com/chen/testAction.java
package com.chen;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Action("/test")
public class testAction {
public void login(HttpServletRequest request,HttpServletResponse response){
System.out.println("login method of the testAtion");
}
}
注解类:
/webFrameWork/src/com/chen/Action.java
package com.chen;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Action {
String value();
}
@Action("/test")
是 对这个Action类进行注解,表明这个当用户请求是/test.do时,调用这个action进行处理,另外,我们也可以根据这个注解来判断一个类是不是Action类。
4. 编写ControllerServlet
首先需要实现init()方法,ControllerServlet在每一次项目运行时进行实例化,会调用init()方法,需要把项目中所有的action记录下来。
我们需要去扫描类路径,并获取所有的action类,我们这里使用一个HashMap来存储。
代码如下:
//用来记录项目的所有action类
private Map<String,Object> map = new HashMap<String,Object>();
@Override
public void init() throws ServletException {
//获取项目字节码文件的绝对路径
String path = this.getServletContext().getRealPath("/WEB-INF/classes");
//扫描文件夹
scanfile(new File(path));
}
/**
* 扫描文件夹
* @param file
*/
private void scanfile(File file) {
if(file.isFile()){
String filename = file.getName();
if(filename.endsWith(".class")){
//如果这个类是action类,加入hashmap
}
}else{
File[] files = file.listFiles();
for(File f : files){
scanfile(f);
}
}
}
那么我们如何判断一个文件是不是action类呢,我们在action类中规定了一个Action注解,所有我们可以通过反射去判断类是否包含这个注解,但是,我们到了这里,只有一个类的字节码的绝对路径,我们需要通过类加载机制来获取这个类。
所以我们再定义一个自定义类加载类:
/webFrameWork/src/com/chen/myClasLoader.java
package com.chen;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class myClasLoader extends ClassLoader{
//为自定义加载类委托父加载类
public myClasLoader(ClassLoader c){
super(c);
}
//获取路劲下类的class对象
public Class load(String path) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream in = new FileInputStream(path);
int n;
byte[] b = new byte[1024];
while((n=in.read(b))!=-1){
out.write(b, 0, n);
}
out.close();
byte[] bytes = out.toByteArray();
return super.defineClass(bytes, 0, bytes.length);
}
}
这样子我们就可以实现servlet的init()方法了,完整代码如下:
//用来记录项目的所有action类
private Map<String,Object> map = new HashMap<String,Object>();
@Override
public void init() throws ServletException {
//获取项目字节码文件的绝对路径
String path = this.getServletContext().getRealPath("/WEB-INF/classes");
//扫描文件夹
try {
scanfile(new File(path));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 扫描文件夹
* @param file
* @throws Exception
*/
private void scanfile(File file) throws Exception {
if(file.isFile()){
String filename = file.getName();
if(filename.endsWith(".class")){
String path = file.getPath();
myClasLoader classloader = new myClasLoader(ControllerServlet.class.getClassLoader());
Class clazz = classloader.load(path);
Action actionannotation = (Action) clazz.getAnnotation(Action.class);
if(actionannotation != null){
map.put(actionannotation.value(), clazz.newInstance());
}
}
}else{
File[] files = file.listFiles();
for(File f : files){
scanfile(f);
}
}
这样子 我们的init()方法就可以实现了,当我们运行项目时,可以记录下所有的action来,下面我们将进行ControllerServlet的处理代码编写。
主要包括一下几点:
- 得到请求的uri
- 截取action的名字 ,获取对应的action类
获取请求的方法并执行
相应的代码如下:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取uri
String uri = request.getRequestURI();
//截取获取到action的名字
uri = uri.substring(request.getContextPath().length(), uri.length()-3);
//获取要相应的action类
Object action = map.get(uri);
if(action == null){
throw new RuntimeException("cannot find the action called " +uri);
}
//获取请求参数的方法
String methodname = request.getParameter("method");
Method method = null;
//通过反射获取到指定的方法
try {
method = action.getClass().getMethod(methodname, HttpServletRequest.class,HttpServletResponse.class);
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException("can not find the method called " + methodname); }
try {
method.invoke(action, request,response);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
到这里 我们的简单框架就完成了,运行项目,然后访问
http://laptop-jicnh2k9:8080/webFrameWork/test.do?method=login
就可以看到相应的输出结果了。
login method of the testAtion