11package com .vison .webmvc .framework ;
22
33import com .google .gson .Gson ;
4+ import com .vison .webmvc .config .App ;
45import com .vison .webmvc .config .Log ;
56import com .vison .webmvc .framework .exception .NullRouteException ;
7+ import java .io .BufferedReader ;
68import java .io .IOException ;
9+ import java .lang .annotation .Annotation ;
10+ import java .lang .reflect .InvocationTargetException ;
711import java .lang .reflect .Method ;
812import java .lang .reflect .Parameter ;
913import java .util .Set ;
14+ import java .util .logging .Level ;
15+ import java .util .logging .Logger ;
1016import javax .servlet .ServletException ;
1117import javax .servlet .annotation .WebServlet ;
1218import javax .servlet .http .HttpServlet ;
2632@ WebServlet (name = "DispatchServlet" , urlPatterns = {"/" })
2733public class DispatchServlet extends HttpServlet {
2834
35+ private Reflections f ;
36+
2937 @ Override
3038 public void init () throws ServletException {
3139 ViewEngine .load (this .getServletContext ());
40+ f = App .f ;
41+
3242 }
3343
3444 @ Override
3545 protected void doGet (HttpServletRequest req , HttpServletResponse resp )
3646 throws ServletException , IOException {
47+ try {
48+ process (req , resp , RequestMethod .GET );
49+ } catch (NullRouteException ex ) {
50+ Logger .getLogger (DispatchServlet .class .getName ()).log (Level .SEVERE , null , ex );
51+ }
52+ }
53+
54+ @ Override
55+ protected void doPost (HttpServletRequest req , HttpServletResponse resp )
56+ throws ServletException , IOException {
57+ try {
58+ process (req , resp , RequestMethod .POST );
59+ } catch (NullRouteException ex ) {
60+ Logger .getLogger (DispatchServlet .class .getName ()).log (Level .SEVERE , null , ex );
61+ }
62+
63+ }
64+
65+ private void process (HttpServletRequest req , HttpServletResponse resp , RequestMethod requestMethod )
66+ throws NullRouteException , IOException {
3767 resp .setContentType ("text/html" );
3868 resp .setCharacterEncoding ("UTF-8" );
3969 String path = req .getRequestURI ().substring (req .getContextPath ().length ());
40- Object res ;
70+ Object res = null ;
4171 try {
42- res = dispatch (path , req , resp );
72+ Method invokeMethod = this .getMaps (path , requestMethod );
73+ switch (requestMethod ) {
74+ case GET :
75+ res = getDispatch (req , resp , invokeMethod );
76+ break ;
77+ case POST :
78+ res = postDispatch (req , resp , invokeMethod );
79+ break ;
80+ }
4381 } catch (NullRouteException ex ) {
4482 res = "404 Not Found" ;
83+ } catch (Exception e ) {
84+ Log .error ("捕获错误" , e );
4585 }
4686 String responseBody = this .handInvokeRes (res );
47- Log .info ("返回信息" , responseBody );
4887 resp .getWriter ().write (responseBody );
4988 resp .getWriter ().flush ();
5089 }
5190
52- private Object dispatch (String path , HttpServletRequest request , HttpServletResponse response )
53- throws NullRouteException {
54- Method method = this .getMaps (path );
91+ private Object getDispatch (HttpServletRequest request , HttpServletResponse response , Method invokeMethod ) {
92+
5593 Object res = null ;
56- Parameter [] parameters = method .getParameters ();
94+ Parameter [] parameters = invokeMethod .getParameters ();
5795 Object [] arguments = new Object [parameters .length ];
5896 for (int i = 0 ; i < parameters .length ; i ++) {
5997 Parameter parameter = parameters [i ];
@@ -80,12 +118,48 @@ private Object dispatch(String path, HttpServletRequest request, HttpServletResp
80118 }
81119 Object obj ;
82120 try {
83- obj = method .getDeclaringClass ().getDeclaredConstructor ().newInstance ();
84- res = method .invoke (obj , arguments );
121+ obj = invokeMethod .getDeclaringClass ().getDeclaredConstructor ().newInstance ();
122+ res = invokeMethod .invoke (obj , arguments );
123+ } catch (Exception e ) {
124+ InvocationTargetException targetEx = (InvocationTargetException ) e ;
125+ Throwable trowEx = targetEx .getTargetException ();
126+ Log .error ("方法invoke失败" , trowEx );
127+ }
128+ return res ;
129+ }
130+
131+ private Object postDispatch (HttpServletRequest request , HttpServletResponse response , Method invokeMethod )
132+ throws IOException {
133+ Object res = null ;
134+ Parameter [] parameters = invokeMethod .getParameters ();
135+ Object [] arguments = new Object [parameters .length ];
136+ for (int i = 0 ; i < parameters .length ; i ++) {
137+ Parameter parameter = parameters [i ];
138+ Log .info ("参数类型" , parameter .getType ());
139+ Class <?> parameterClass = parameter .getType ();
140+ if (parameterClass == HttpServletRequest .class ) {
141+ arguments [i ] = request ;
142+ } else if (parameterClass == HttpServletResponse .class ) {
143+ arguments [i ] = response ;
144+ } else if (parameterClass == HttpSession .class ) {
145+ arguments [i ] = request .getSession ();
146+ } else {
147+ // 读取JSON并解析为JavaBean:
148+ request .setCharacterEncoding ("UTF-8" );
149+ BufferedReader reader = request .getReader ();
150+ Gson gson = new Gson ();
151+ arguments [i ] = gson .fromJson (reader , parameterClass );
152+ }
153+ }
154+ Object obj ;
155+ try {
156+ obj = invokeMethod .getDeclaringClass ().getDeclaredConstructor ().newInstance ();
157+ res = invokeMethod .invoke (obj , arguments );
85158 } catch (Exception e ) {
86159 Log .error ("方法invoke失败" , e );
87160 }
88161 return res ;
162+
89163 }
90164
91165 private String getOrDefault (HttpServletRequest request , String name , String defaultValue ) {
@@ -108,22 +182,27 @@ private String handInvokeRes(Object obj) {
108182 return jsonRes ;
109183 }
110184
111- private Method getMaps (String path ) throws NullRouteException {
112-
113- String packageName = "com.vison.webmvc.controller" ;
114- ConfigurationBuilder config = new ConfigurationBuilder ();
115- config .filterInputsBy (new FilterBuilder ().includePackage (packageName ));
116- config .addUrls (ClasspathHelper .forPackage (packageName ));
117- config .setScanners (new MethodAnnotationsScanner ());
118- Reflections f = new Reflections (config );
119- Set <Method > resources = f .getMethodsAnnotatedWith (GetMapping .class );
185+ private Method getMaps (String path , RequestMethod requestMethod ) throws NullRouteException {
120186
121- for (Method method : resources ) {
122- GetMapping annotation = method .getAnnotation (GetMapping .class );
123- if (path .equals (annotation .path ())) {
124- return method ;
187+ if (requestMethod == RequestMethod .GET ) {
188+ Set <Method > resources = f .getMethodsAnnotatedWith (GetMapping .class );
189+ for (Method method : resources ) {
190+ GetMapping annotation = method .getAnnotation (GetMapping .class );
191+ if (annotation .path ().equals (path )) {
192+ return method ;
193+ }
125194 }
126195 }
196+ if (requestMethod == RequestMethod .POST ) {
197+ Set <Method > resources = f .getMethodsAnnotatedWith (PostMapping .class );
198+ for (Method method : resources ) {
199+ PostMapping annotation = method .getAnnotation (PostMapping .class );
200+ if (annotation .path ().equals (path )) {
201+ return method ;
202+ }
203+ }
204+ }
205+
127206 throw new NullRouteException ();
128207 }
129208}
0 commit comments