首页 > 代码库 > Jetty数据同步使用

Jetty数据同步使用

1. Jetty简介

  Jetty 是一个开源的servlet容器,它为基于Java的web容器,例如JSP和servlet提供运行环境。Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布。开发人员可以将Jetty容器实例化成一个对象,可以迅速为一些独立运行(stand-alone)的Java应用提供网络和web连接

2. 项目工作中的使用

     近期项目中需要同步业务方的相关数据,因此打算使用Jetty完成此目标,具体的代码信息如下:

     (1) 封装Jetty的服务类

public class JettyServerController {

    private Server jettyServer;
    private int jettyServerPort = 1999;
    private String contextPathString;
    private String startPageString;
    private boolean jettyDirectoryListed = false;
    private HashMap<String, Servlet> servletInstanceHashMap = new HashMap<String, Servlet>();

    /**
     * Creates an instance of the jettyServer on the portJettyServer
     * 
     * @param jettyServerPort
     */
    public JettyServerController( int jettyServerPort, String startPageString, String contextPathString, boolean jettyDirectoryListed ) 
    {
        // set the start page string
        if (startPageString != null)
            this.startPageString = startPageString;

        // set the context path string
        if (contextPathString != null)
            this.contextPathString = contextPathString;
        
        // set the directory listing property
        this.jettyDirectoryListed = jettyDirectoryListed;

        // set the jetty operating port
        this.jettyServerPort = jettyServerPort;

        // bounds check and assign the input port
        if ( jettyServerPort < 65536 && jettyServerPort > 1000) {
            this.jettyServerPort = jettyServerPort;
        }

        // create a new jetty server instance
        jettyServer = new Server();

        // Set up a channel selector object
        SelectChannelConnector connector = new SelectChannelConnector();

        // set the port number
        connector.setPort( this.jettyServerPort );

        // add the connector to the server
        jettyServer.addConnector( connector );

    }

    public void setHandler(ContextHandlerCollection contexts) {
        jettyServer.setHandler(contexts);
    }

    public void startAndLaunchBrowser() throws Exception {
        // Create the resource handler
        ResourceHandler resource_handler = new ResourceHandler();

        // disallow directory listing
        resource_handler.setDirectoriesListed( this.jettyDirectoryListed );

        // Set the initial load file
        resource_handler.setWelcomeFiles(new String[] { this.startPageString });

        // point to the local directory
        resource_handler.setResourceBase(".");
        
        // use sessions
        ServletContextHandler servletContextHandler = new ServletContextHandler(
                ServletContextHandler.SESSIONS);

        // set /web as the default path
        servletContextHandler.setContextPath( this.contextPathString );

        // add the handler
        jettyServer.setHandler( servletContextHandler );
        
        // get the servlets
        for (String servletPath : servletInstanceHashMap.keySet()) {
            // add a servlet
            servletContextHandler.addServlet(new ServletHolder(
                    servletInstanceHashMap.get( servletPath )), servletPath);
        }

        // create a handler list
        HandlerList handlers = new HandlerList();

        // add three handlers
        handlers.setHandlers( new Handler[] { servletContextHandler,
                resource_handler, new DefaultHandler() });

        // pass the handlers to the server
        jettyServer.setHandler(handlers);
        
        // start the session
        jettyServer.start();
    }

    public void stop() throws Exception {
        jettyServer.stop();
        jettyServer.join();
    }
    
    public void join() throws InterruptedException{
        jettyServer.join();
    }

    public boolean isStarted() {
        return jettyServer.isStarted();
    }

    public boolean isStopped() {
        return jettyServer.isStopped();
    }
    
    public void addServlet( String servletPath, Servlet servlet )
    {
        servletInstanceHashMap.put( servletPath, servlet);
    }
    
    public void removeServlet ( String servletPath )
    {
        servletInstanceHashMap.remove( servletPath );
    }

}

       (2) 插入Servlet组件

public class ServletHelper {
    private  static final Logger logger = LoggerFactory.getLogger(ServletHelper.class);

    public static void main(String[] args) throws Exception {      
        initJetty(8080);
    }

    public static void initJetty(int port) throws Exception {
        // Create a new JettyServerController
        JettyServerController controller = new JettyServerController(port,"/query","/",true);
        controller.addServlet("/test", new TestServlet());

        // start the session and launch the default page
        controller.startAndLaunchBrowser();
        System.in.read();

        controller.stop();// stop the local Jetty ajax services
    }
}

        (3) Servlet业务功能

        接收业务方POST请求发送的数据,并存储至数据库

public class TestServlet extends HttpServlet{

    private static final long serialVersionUID = -2385860009337093194L;
    
    private static final int SUCCESS = 0;
    private static final int FAILED = -1;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter out = resp.getWriter();

        int resultCode = -1;
        String info = "";
        // 获取参数
        String para = "";
        try {
            para = req.getParameter("para");
        } catch (Exception e) {
        }
        if(para.trim().length() == 0){
            resultCode = FAILED;
        }else{
            byte[] buffer = getRequestPostBytes(req);
            if(buffer == null || buffer.length == 0){
                resultCode = FAILED;
            }else{
                String charEncoding = req.getCharacterEncoding();
                if(charEncoding == null) charEncoding = "UTF-8";
                info = new String(buffer,charEncoding);
                // 将获取的信息更新至数据库
        ......
            }
        }

        JSONObject result = new JSONObject();
        result.put("resultCode",resultCode);
        result.put("content",info);

        resp.addHeader("resultCode",""+resultCode);
        out.print(result.toString());

        LogUtil.info(result.toString());

    }

    byte[] getRequestPostBytes(HttpServletRequest request) throws IOException{
        int length = request.getContentLength();
        if(length == 0){
            return null;
        }

        byte buffer[] = new byte[length];
        for(int i = 0; i < length;){
            int readLen = request.getInputStream().read(buffer, i, length-i);
            if(readLen == -1) break;
            i += readLen;
        }
        return buffer;
    }
}

 

Jetty数据同步使用