设为首页 收藏本站
查看: 669|回复: 0

[经验分享] jetty的一个小程序

[复制链接]

尚未签到

发表于 2017-2-26 10:33:33 | 显示全部楼层 |阅读模式
用jetty写了一个小程序,主要是解决局域网内很多人不能上网的问题.我的想法是通过一台可以上网的主机,启动这个服务.其他人访问他就可以浏览网页.写的很糙.不过能跑,有的页面还是有问题.

思路:

浏览器   -->    jetty服务,httpclient(这里的url写死的 http://www.google.cn/search?q= 查询内容)   -->   google
浏览器   <--    这里有流操作,把一些url替换掉                                                    <--   google

一下都是一样的,还有翻页也没写. get提交加一个 属性start=0 或10 20 ...   

不过感觉很慢,就是随便写着玩的.  希望大家给点意见.   

图片为要导入的包.

package Jetty_Test.mytest;

import java.util.Random;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.HashSessionIdManager;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.thread.BoundedThreadPool;

public class JettyMain implements Constant{
    static Server server;

    static {
        server = new Server();
    }

    public static void startserver() {
        // Service对象就是Jetty容器,实例化出这样一个对象就产生了一个容器。
        server.setSessionIdManager(new HashSessionIdManager(new Random()));
        server.setStopAtShutdown(true);

        BoundedThreadPool pool = new BoundedThreadPool();
        pool.setLowThreads(minThreads);
        pool.setMaxThreads(maxThreads);
        server.setThreadPool(pool);

        Connector connector = new SelectChannelConnector();
        connector.setPort(httpPort);
        connector.setHost(ipStr);
        server.addConnector(connector);

        Context context = new Context(server, "/", Context.SESSIONS);
        context.addServlet(new ServletHolder(new MainServlet()), context_Main+"/*");
        context.addServlet(new ServletHolder(new GoogleServlet()), context_Google+"/*");
        context.addServlet(new ServletHolder(new PageServlet()), context_Page+"/*");
        // HandlerCollection handlers = new HandlerCollection();
        // ContextHandlerCollection contexts = new ContextHandlerCollection();
        // RequestLogHandler requestLogHandler = new RequestLogHandler();
        // handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(),
        // requestLogHandler });
        // server.setHandler(handlers);
      
//        ContextHandlerCollection contexts = new ContextHandlerCollection();
//        server.setHandler(contexts);
//
//        WebAppContext webapp = new WebAppContext(contexts, "webapp", "/testjsp");
//        SessionManager session = webapp.getSessionHandler().getSessionManager();
//
//        HandlerCollection handlers = new HandlerCollection();
//        handlers.setHandlers(new Handler[] { context, webapp });
//        server.setHandler(handlers);

        // Handler handler = new MyHandelr();
        // server.setHandler(handler);
        try {
            server.start();
            // server.join();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String args[]) {
        startserver();
    }
}







package Jetty_Test.mytest;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;

public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = -5499674229427179325L;

    static byte[] buf;

    static {
        InputStream file = null;
        ByteArrayOutputStream out = null;
        try {
            file = new FileInputStream(Constant.filePath);
            out=new ByteArrayOutputStream();
           
            int temp=file.read();
            while(temp!=-1){
                out.write(temp);
                temp=file.read();
            }
            buf=out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    public void init() throws ServletException {
        super.init();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();
        base_request.setHandled(true);

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(buf);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}













package Jetty_Test.mytest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class PageServlet extends HttpServlet {
    public void init() throws ServletException {
        super.init();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String urlstr = request.getParameter("urlstr");
//        System.out.println("PageServlet url:" + urlstr);

        if (urlstr == null) {
            urlstr = "";
        }

        // urlstr = URLEncoder.encode(urlstr);
        HttpClient httpclient = new HttpClient();
        GetMethod postMethod = new GetMethod(urlstr);
        httpclient.executeMethod(postMethod);

        InputStream input = postMethod.getResponseBodyAsStream();
        response.setCharacterEncoding("uft8");
        OutputStream out = response.getOutputStream();

        Help.analyse(input, out);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}














package Jetty_Test.mytest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class GoogleServlet extends HttpServlet {
    private static final long serialVersionUID = 8306441036467951814L;

    public void init() throws ServletException {
        super.init();
    }

    public static void main(String args[]) throws UnsupportedEncodingException {
        String str = "a";
        byte[] bs = str.getBytes("utf8");
        // byte[] bs=str.getBytes("gbk");
        for (int i = 0; i < bs.length; i++) {
//            System.out.println(bs + "");
        }
//        System.out.println();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String searchcontext = request.getParameter("searchcontext");
        if (searchcontext == null) {
            searchcontext = "";
        }
        String URLTest = "http://www.google.cn/search?q=" + URLEncoder.encode(searchcontext);
        HttpClient httpclient = new HttpClient();
        GetMethod postMethod = new GetMethod(URLTest);
        httpclient.executeMethod(postMethod);

        InputStream input = postMethod.getResponseBodyAsStream();
        response.setCharacterEncoding("uft8");
        OutputStream out = response.getOutputStream();

        Help.analyse(input, out);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}




package Jetty_Test.mytest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class Help implements Constant{
    private static byte[] handleALine(byte[] buff) throws UnsupportedEncodingException {
        StringBuilder str = new StringBuilder();
        if (buff[9] == 'h' && buff[10] == 't' && buff[11] == 't' && buff[12] == 'p') {
            str.append("a href=\"http://" + ipStr + ":" + httpPort + context_Page + "?urlstr=");

            for (int i = 9; i < buff.length; i++) {
                if (buff == '"') {
                    break;
                }
                str.append((char) buff);
            }

            str.append("\"");
        } else {
            str.append("a href=\"http://" + ipStr + ":" + httpPort + context_Main +"\"");
        }
        // System.out.println(str.toString());
        byte[] bss = str.toString().getBytes("utf8");
        return bss;
    }

    public static void analyse(InputStream input, OutputStream out) throws IOException {
        byte[] buff = null;
        int flg = 0;
        int flga = 0;
        long num = 0;
        int index = 0;

        int temp = input.read();
        while (temp != -1) {

            num++;
            if (temp == '<') {
                flg = 1;
                num = 1;
            } else if (temp == 'a') {
                if (flg == 1 && num == 2) {
                    flga = 1;
                    buff = new byte[2048];
                    buff[index] = '<';
                    index++;
                } else {
                    flg = 0;
                }
            } else if (temp == '>') {
                if (flga == 1) {
                    buff[index] = (byte) temp;
                    index++;

                    for (int i = 0; i < buff.length; i++) {
                        // System.out.print((char) buff);
                    }
                    byte[] bss = handleALine(buff);
                    for (int i = 0; i < bss.length; i++) {
                        out.write(bss);
                    }
                    // System.out.println();
                }
                flg = 0;
                flga = 0;
                index = 0;
            } else {

            }

            if (flga == 1) {
                buff[index] = (byte) temp;
                index++;
            } else {
                out.write(temp);
            }
            temp = input.read();
        }

        input.close();
        out.close();
    }
}



package Jetty_Test.mytest;

public interface Constant {
    static String context_Main = "/index";
    static String context_Google = "/google";
    static String context_Page = "/pageshow";

    static int minThreads = 5;
    static int maxThreads = 10;
   
    static String ipStr = "192.168.1.5";
    static int httpPort = 12345;
   
    static String filePath="src/Jetty_Test/mytest/start.txt";
}



start.txt文件

<html>
<body>

<form action="http://192.168.1.5:12345/google" method="get">
google搜索 请输入你要搜索的内容:
<input type="text" name="searchcontext">
<input type="submit" value="提交">
</form>
<p/>
<b>mgt 测试</b><br/>
<a href="http://200.eff.com:81/trunk/index.jsp" target="_blank">黄师傅 mgt</a>  http://200.eff.com:81/trunk/index.jsp <br/>
<a href="http://163.eff.com:88/trunk/" target="_blank">163 mgt</a>  http://163.eff.com:88/trunk/
<p/>

<b>总控查看</b><br/>
<a href="https://192.168.0.73/list.jsp" target="_blank">23 总控</a>  https://192.168.0.73/list.jsp  <br/>
<a href="https://192.168.0.173/list.jsp" target="_blank">25 总控</a>  https://192.168.0.173/list.jsp
<p/>

<b>eim服务查看</b><br/>
<a href="http://192.168.0.23:5227/admin/login.jsp" target="_blank">23 eim控制</a>  http://192.168.0.23:5227/admin/login.jsp <br/>
<a href="http://192.168.0.25:5227/admin/login.jsp" target="_blank">25 eim控制</a>  http://192.168.0.25:5227/admin/login.jsp
<p/>

<b>测试客户端</b><br/>
<a href="http://192.168.0.10/" target="_blank">测试客户端</a>  http://192.168.0.10/ <p/>

<b>工具下载</b><br/>
<a href="ftp://192.168.2.1/" target="_blank">工具下载</a>  ftp://192.168.2.1/ <p/>

<b>bug管理</b><br/>
<a href="http://192.168.0.3/TDBIN/start_a.htm" target="_blank">bug管理(td)</a>  http://192.168.0.3/TDBIN/start_a.htm <p/>

<b>svn地址</b><br/>
<a href="#">svn地址</a>  https://192.168.0.2/svn/server <p/>

<b>Search URL</b><br/>
<a href="#">更新全部的doc 注意ip地址: </a>  http://192.168.0.182:8089/search/action/?action=updateAll <br/>
<a href="#">优化单个公司索引 注意ip地址: </a>  http://192.168.0.182:8089/search/action/?action=optimizeAll <br/>
<a href="#">更新单个的doc 注意ip地址,公司id: </a>  http://192.168.0.25:8089/search/action/?corpID=5349&action=update <br/>
<a href="#">优化单个公司索引 注意ip地址,公司id: </a>  http://192.168.0.182:8089/search/action/?corpID=5349&action=optimize <p/>





</body>
</html>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-347347-1-1.html 上篇帖子: jetty一个开源的servlet容器 下篇帖子: equinox web开发依赖包(jetty)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表