Write your own servlet Dispatchar for ease of use in OSGi

Source: Internet
Author: User

The MVC framework, such as SPRINGMVC, is temporarily unsupported in OSGi, and when we write a method, we need to create a new servlet, which is cumbersome, so we want to implement an MVC framework that works in an OSGi environment, mimicking the SPRINGMVC or struts2 framework.

1. First we look at the configuration of Web. Xml. It defines a servlet that filters all URIs with. Do, and initializes the parameters with the controller class. When the container starts, the servlet's Init method is executed, and the controller class is initialized. For later invocation.

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "3.0" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "><display-name></display-name>< Welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet ><servlet-name>dispatcher</servlet-name><servlet-class>com.yyc.servlet.dispatcher</ Servlet-class><init-param><param-name>login</param-name><param-value> com.yyc.controller.login</param-value></init-param><init-param><param-name>main</ param-name><param-value>com.yyc.controller.main</param-value></init-param>< Load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name> Dispatcher</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping></web-app> 


2.dispatchar.java inherits the servlet, overwriting the Init method, and Doget the Dopost method. Init initializes the controller class to the map and, if there is a UIR request, intercepts the requested UiR to get the class, and the method name.

Then use the Java reflection mechanism to execute.

Package Com.yyc.servlet;import Java.io.ioexception;import Java.lang.reflect.invocationtargetexception;import Java.util.enumeration;import Java.util.hashmap;import Java.util.map;import Javax.servlet.servletconfig;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Dispatcher Extends HttpServlet {/** * */private static final long serialversionuid = 1L; map<string, object> controllers = new hashmap<string, object> ();p rivate servletcontext application = null;//  A Web application corresponds to a servletcontextprivate servletconfig config = null; One servlet corresponds to a servletconfig@overridepublic void init () throws servletexception{//Create Controller bean//Read the Web. XML configuration parameter Put controllersapplication = Getservletcontext (); config = Getservletconfig (); Enumeration<string> enumeration = Config.getinitparameternames (); while (enumeration.hasmoreelementS ()) {String className = enumeration.nextelement ();//Get the parameter beanfactory by getting init (ClassName, Config.getinitparameter ( ClassName));} Super.init ();} @Overridepublic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, response);} @Overridepublic void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {String uri = Request.getrequesturi (); String classmethodname = uri.substring (Uri.lastindexof ("/") +1,uri.lastindexof (". Do"); String className = Classmethodname.split ("_") [0]; String methodName = Classmethodname.split ("_") [1];object controller = controllers.get (className); try { Controller.getclass (). GetMethod (Methodname,new Class[]{httpservletrequest.class,httpservletresponse.class}). Invoke (Controller.getclass (). newinstance (), New Object[]{request,response}); catch (IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) { TODO AUto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( InvocationTargetException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Nosuchmethodexception e) {/ /TODO auto-generated catch Blocke.printstacktrace ();} catch (Instantiationexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public void Beanfactory (String classname,string classPath) {try {class<?> clazz = class.forname (ClassPath); Controllers.put (ClassName, Clazz.newinstance ()); SYSTEM.OUT.PRINTLN ("Initialization class" +classname);} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Instantiationexception  e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//Todo auto-generated catch Blocke.printstacktrace ();}}}

The following is the controller class

Login.java

Package Com.yyc.controller;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Login {public void In (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {System.out.println ("Login!" "); Response.sendredirect (" index.jsp ");} public void out (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.getwriter (). Print ("You  logout!"); SYSTEM.OUT.PRINTLN ("Exit! ");}}

Main.java

Package Com.yyc.controller;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Main {public void Index (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { System.out.println ("Go to homepage! ");}}


3. Test call, using Tomcat

After startup, you can call this:

Http://localhost:8080/dispatcher/login_in.do login needs to correspond to the value of the servlet corresponding parameter in Web. XML, in is the method name within the corresponding class
Http://localhost:8080/dispatcher/login_out.do

Http://localhost:8080/dispatcher/main_index.do

The simplest distribution functionality is implemented here to reduce redundant configuration, next study of OSGi ' Blueprint for configuration processing, and dependency injection


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Write your own servlet Dispatchar for ease of use in OSGi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.