How do I get the URL of the web page a Java Applet

2019-05-07 06:19发布

I am making an applet in Java that will be embedded into a web page, but the URL of the page is dynamic. I need to be able to get the current URL of the page that the applet is running on. Does anyone know how to do this?

标签: java url applet
2条回答
仙女界的扛把子
2楼-- · 2019-05-07 06:41

It should work like this:

[YourApplet].getCodeBase();

This method returns you the URL object. Then you obtain what you need :)

查看更多
叼着烟拽天下
3楼-- · 2019-05-07 06:47

See getDocumentBase()


Using getDocumentBase() actually gave me a NullPointerException..

It works fine here. I just tested it using this code.

// <applet code=MyLocation width=400 height=30></applet>
import javax.swing.*;

public class MyLocation extends JApplet {

    @Override
    public void init() {
        add( new JLabel(getDocumentBase().toString()));
    }
}

To compile & run it, do the following after saving the source.

prompt> javac MyLocation.java
prompt> appletviewer MyLocation.java

The .java extension on the second line is no typo. Recent versions of applet viewer will look in the specified source code for an applet element defined in a comment.

查看更多
登录 后发表回答