run applet in web application

后端 未结 3 557
悲&欢浪女
悲&欢浪女 2020-12-10 06:29

I want to run simple applet in my web application using html applet tag but it gives error like

java.lang.ClassNotFoundException: MyApplet

please, give me

3条回答
  •  鱼传尺愫
    2020-12-10 07:02

    Old thread, I know... but I've come up with a little hack that allows you to serve applets that are inside your WEB-INF/classes folder so that you don't need an extra jar in your project (and you can redeploy your applet a little faster). The downside of this is that you can't sign your applet (because it's a .class not a jar). Let's cut to the chase here...

    First, create a little servlet that serves applets (it requires Javassist):

    public class AppletServlet implements Servlet {
    ...
    ClassPool pool = ClassPool.getDefault();
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        pool.insertClassPath(new ClassClassPath(this.getClass()));
    }
    
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        String className = ((HttpServletRequest) req).getPathInfo().substring(1);
        try {
            CtClass cc = pool.get(className.replace("/", ".").replace(".class", ""));
            res.setContentType("application/x-java-applet;version=1.5.0");
            res.setContentLength(cc.toBytecode().length);
            res.getOutputStream().write(cc.toBytecode());
            res.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    ...
    }
    

    Now declare your AppletServlet (I know, terrible name) as a servlet in your web.xml:

    
        Applet Servlet
        com.example.AppletServlet
    
    
        Applet Servlet
        /applet/*
    
    

    Finally, invoke your applet from your page:

    
        
        
        
        Applet failed to run. No Java plug-in was found.
    
    

    And that's it. The servlet will use Javassist to get the byte code for your class and serve it to the request.

    Disclaimer If someone knows your package structure, they could download all the classes and do evil things from there. So make sure you only allow the servlet to serve classes that are actually applets.

提交回复
热议问题