HtmlUnit Javascript Engine – Do you need it?

The Rhino engine used by HtmlUnit is great but can be slow. If you are worried about performance you can ask yourself whether you really need it. You can always enable it if you need it.

These are the settings I am currently using which is quick enough for me a the moment.


public class HtmlUnitWebClient extends WebClient {

    public HtmlUnitWebClient() {

super(BrowserVersion.CHROME);
super.setIncorrectnessListener(new IncorrectnessListenerImpl() {
@Override
public void notify(String arg0, Object arg1) {
//do nothing
}
});

final SilentCssErrorHandler eh = new SilentCssErrorHandler();
super.setCssErrorHandler(eh);
super.getOptions().setThrowExceptionOnScriptError(false);
super.getOptions().setThrowExceptionOnFailingStatusCode(false);
super.getOptions().setUseInsecureSSL(true);
       super.getOptions().setCssEnabled(false);
       super.getOptions().setPopupBlockerEnabled(false);
       super.getOptions().setRedirectEnabled(true);
      super.getOptions().setJavaScriptEnabled(false);
      super.setJavaScriptTimeout(3600);
super.getOptions().setTimeout(9000);
setCookieManager(new CookieManager() {
protected int getPort(final URL url) {
final int r = super.getPort(url);
return r != -1 ? r : 80;
}
});

}

}

Using the Spring Container for new instances

One of the most common mistakes when using  Spring IOC is using the new()  to create a new instance. If you instantiate a bean this way it won’t be picked up the Spring container and you lose all the magic that comes with IOC.

  1. When you create the class make sure you use the prototype scope
    @Component
    @Scope(value=”prototype”)
    Class MyClass {
    ……..
  2. Autowire the context into the bean
    @Autowired
    private ApplicationContext context;
  3. Instantiate the bean in your code
    MyNewClass myObject = context.getBean(MyNewClass.class)

And you’re done. The fact that we’re still creating beans using factories can easily be forgotten when we are using annotations. However you can still do things the old way.