Jar Pack Preparation: Servlet-api-3.0.jar
The project structure is as follows:
annotation mapping, for mapping URL addresses
/* * file name: Action.java
* Copyright 2007-2016 517na Tech. Co. Ltd. All rights Reserved.
* Description: Action.java
* Modified by: Peiyu
* Modified: July 29, 2016
* Modified: NEW */
package
com.servlet3.annotation;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Target ({elementtype.method,elementtype.type})
@Retention (retentionpolicy.runtime) public
@interface Mapping {
String value ();
}
Actionmodel, for encapsulating action information
/* * File name: Actionmodel.java * Copyright 2007-2016 517na Tech. Co. Ltd.
All rights Reserved.
* Description: Actionmodel.java * Modified by: Peiyu * Modified: August 1, 2016 * Modified: NEW */Package com.servlet3.util;
Import java.io.Serializable;
Import Java.lang.reflect.Method;
/** * @author Peiyu * */public class Actionmodel implements serializable{/** * Add field comments.
*/private static final long serialversionuid = 1L;
Private String ClassName;
Private Method method;
Private Object action;
/** * Set classname.
* @return Return ClassName */public String GetClassName () {return className;
}/** * get classname. * @param className to set ClassName */public void Setclassname (String className) {this.classname = Classna
Me
}/** * Set method.
* @return Return Method */Public method GetMethod () {return method;
}/** * Gets method. * method to be set for @param method */public voidSetmethod (method) {This.method = method;
}/** * Set action.
* @return Return action */public Object getaction () {return action;
}/** * Gets the action.
* @param action to set the action */public void setaction (Object action) {this.action = action;
}
}
myfilter Filter, creating annotations that scan all classes under the specified package when initializing, parsing URLs, creating beans
/* * File name: Myfilter.java * Copyright 2007-2016 517na Tech. Co. Ltd.
All rights Reserved.
* Description: Myfilter.java * Modified by: Peiyu * Modified: July 29, 2016 * Modified: NEW */Package com.servlet3.filter;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.lang.annotation.Annotation;
Import Java.lang.reflect.Method;
Import Java.net.URLDecoder;
Import Java.util.HashMap;
Import Java.util.Map;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.annotation.WebFilter;
Import Javax.servlet.http.HttpServletRequest;
Import com.servlet3.annotation.Mapping;
Import com.servlet3.exception.URLException;
Import Com.servlet3.util.ActionModel;
Import com.servlet3.util.CommentedProperties; /** * * @author Peiyu */@WebFilter (filtername = "Myfilter", Urlpatterns = {"/* "}) public class Myfilter implements Filter {@Override public void Destroy () {Syste
M.out.println ("-----------------------destroy-----------------------"); } @Override public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws Ioexc
Eption, servletexception {httpservletrequest httpservletrequest = (httpservletrequest) request;
String uri = Httpservletrequest.getrequesturi ();
The logical address of the access/myservlet3 String URL = uri.substring (Uri.indexof ("/", 1));
Httpservletrequest.getrequesturl ();
System.out.println ("-----------------------doFilter-----------------------");
Request.setattribute ("url", url);
Request.getrequestdispatcher ("/myservlet3"). Forward (Request,response); }/** * * *. Gets the package name that is configured in the configuration file to be scanned. Scan annotations based on package name, get URL, create bean instance */@Override public void init (Filterconfig config) throws servletexception {// Getting packages in a configuration filePath Commentedproperties properties = new Commentedproperties (); /d:/software/apache-tomcat-7.0.59/webapps/servlet3.0/web-inf/classes/scan-package.properties String ClassPath
= MyFilter.class.getClassLoader (). GetResource (""). GetPath ();
String Path = ClassPath + "Scan-package.properties";
System.out.println ("# # #1加载配置文件:" + path);
try {path = Urldecoder.decode (path, "UTF-8");
} catch (Unsupportedencodingexception E1) {e1.printstacktrace ();
} System.out.println ("# # # #2加载配置文件:" + path);
try {properties.load (new FileInputStream (path), "UTF-8");
} catch (IOException e) {e.printstacktrace ();
}//gets to the package path String scanpackage = Properties.getproperty ("Scan-package"). Replace (".", "/"); /*************************** All files under the scan package ***************************************///Get to the class file path = Clas
spath + scanpackage; map<string, actionmodel> urls = new hashmap<> ();
File File = new file (path);
Get action,url information getfileurls (file, URLs);
Place Action,url information in ServletContext config.getservletcontext (). SetAttribute ("URLs", URLs);
}/** * Gets the URL. */private void Getfileurls (file file, map<string, actionmodel> URLs) {if (File.isdirectory ()) {///if it is a text
folder, get files under Folders file[] files = file.listfiles ();
for (File temp:files) {if (Temp.isdirectory ()) {Getfileurls (temp, URLs);
} else {Getfileurl (temp, URLs);
}}} or else {//If it is a file Getfileurl (files, URLs);
}}/** * Gets the URL to create the action bean.
*/@SuppressWarnings ("rawtypes") private void Getfileurl (File temp, map<string, actionmodel> URLs) {
String path;
Path = Temp.getpath (); STring ClassName = path.substring (path.indexof ("com"), Path.lastindexof (".")).
Replace ("\ \", ".");
try {Class clazz = Class.forName (className);
Get class annotations String StartURL = "";
annotation[] annotations = clazz.getannotations ();
for (Annotation annotation:annotations) {//if (Annotation instanceof Mapping) {//judgment is Mapping
StartURL = ((Mapping) annotation). Value (); }//} if (Clazz.isannotationpresent (Mapping.class)) {StartURL = ((Mapping) c
Lazz.getannotation (Mapping.class)). Value ();
}//Get annotations on method method[] methods = Clazz.getmethods ();
Object action=clazz.newinstance (); for (Method method:methods) {if (Method.isannotationpresent (Mapping.class)) {actio
Nmodel Actionmodel = new Actionmodel (); Actionmodel.setclassnamE (className);
Actionmodel.setmethod (method);
Actionmodel.setaction (action);
Mapping annotation=method.getannotation (Mapping.class);
String key = StartURL + ((Mapping) annotation). Value ();
if (Urls.containskey (key)) {throw new Urlexception ("already exists URL:" + key);
} else {urls.put (key, Actionmodel);
}}//annotations = Method.getannotations ();
for (Annotation annotation:annotations) {//if (Annotation instanceof Mapping) {//judgment is Mapping
Actionmodel actionmodel=new Actionmodel ();
Actionmodel.setclassname (ClassName);
Actionmodel.setmethod (method);
Actionmodel.setaction (action); String key = StartURL + ((Mapping) annotation). value ();
if (Urls.containskey (key)) {//throw new Urlexception ("already exists URL:" +key);
}else {//Urls.put (key, Actionmodel); }//}//}}} catch (Exception e) {e.prints
Tacktrace ();
}
}
}
scan-package.properties Configuring packages that need to be scanned
Scan-package=com.servlet3.controller
Default-accessed servlet, which finds the specified URL address through the servlet
/* * File name: Myservlet3.java * Copyright 2007-2016 517na Tech. Co. Ltd.
All rights Reserved.
* Description: Myservlet3.java * Modified by: Peiyu * Modified: July 29, 2016 * Modified: NEW */Package com.servlet3.controller;
Import java.io.IOException;
Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebInitParam;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Com.servlet3.util.ActionModel; /** * Name: The name of the current servlet * urlpatterns: Requested URL * Loadonstartup:tomcat Initialize the servlet at startup * InitParams: Initialize parameter * Name: Parameter name * Value: Parameter value * * @author Peiyu */@WebServlet (name = "MyServlet3", Urlpatterns = {"/myservlet3"}, Loadonstartup = 1, I Nitparams = {@WebInitParam (name = "Name", value = "java"), @WebInitParam (name = "Age", value = "1")}
public class MyServlet3 extends HttpServlet {/** * add field comments.
*/Private static final long serialversionuid = 1L; @SuppressWarnings ({"Unchecked"}) @Override protected void doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {string url= (string) req.getattribute ("url");
map<string, actionmodel> urls = (map<string, actionmodel>) Req.getservletcontext (). GetAttribute ("URLs");
Actionmodel actionmodel=urls.get (URL); if (actionmodel!=null) {try {Object Res=actionmodel.getmethod (). Invoke (Actionmodel.getaction
(), REQ,RESP); Based on the returned result type, the return value is processed if (res instanceof String) {if ((String) res). StartsWith ("Redire CT: ")) {//...}
else if ((String) res). StartsWith ("Forward:")) {//...}
}else{//...}
} catch (Exception e) { E.printstacktrace (); }}} @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servle
Texception, IOException {doget (req, resp);
}
}
useraction of the test
/* * file name: Useraction.java
* Copyright 2007-2016 517na Tech. Co. Ltd. All rights Reserved.
* Description: Useraction.java
* Modified by: Peiyu
* Modified: July 29, 2016
* Modified: NEW */
package
Com.servlet3.controller ;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import com.servlet3.annotation.Mapping;
/**
* @author peiyu
*
/@Mapping (value= "/myservlet3") public
class Useraction {
@ Mapping (value= "/login") Public
String Login (httpservletrequest req, HttpServletResponse resp) {
SYSTEM.OUT.PRINTLN ("--------login-------------");
return "Redirect:register";
}
Register
@Mapping (value= "/register") Public
String Register (httpservletrequest req, HttpServletResponse resp) {
System.out.println ("--------Register-------------");
return "Redirect:login";
}
}
Finally, start the server, and access http://localhost:8072/Servlet3.0/myServlet3/login?name=java&age=1 will find the Useraction login method.