Servlet cannot serve a simple applet - java

I have a simple applet that i want to show on a local webpage that is connected with my server and servlet.
Applet code:
public class MyApplet extends JApplet implements ActionListener {
JPanel panel = new JPanel();
JButton btnPush;
public MyApplet() {}
public void init() {
createGUI();
}
public void createGUI() {
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
btnPush = new JButton("Push");
btnPush.addActionListener(this);
btnPush.setBounds(54, 94, 89, 23);
panel.add(btnPush);
setSize(200, 200);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnPush) {
JOptionPane.showMessageDialog(this, "Button was pushed");
}
}
}
Here's the servlet/server code:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; chaset=utf-8");
Writer writer = response.getWriter();
writer.write("<applet codebase=\"bin\" code=\"MyApplet.class\" width=\"200\" height=\"200\">" +
"If your browser was Java-enabled, a button would appear here. </applet>");
}
public static void main(String... args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(MyServlet.class, "/");
MyApplet applet = new MyApplet();
applet.init();
applet.start();
Server server = new Server(8080);
server.setHandler(context);
server.start();
server.join();
}
}
I'm using servlet-api3.0 and jetty 8.
I can connect to http://"localhost:8080", but when my applet trying to load it stops loading.
When i running a html file with applet tag it works without any problem. So it seems like the servlet is the trouble here. Have i forgot something?

The configuration for your Server can only respond to the Servlet itself.
There is no DefaultServlet setup to actually return the MyApplet.class file that is being requested.
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// Serve content from bin directory (where the classes are compiled into)
ServletHolder holder = context.addServlet(DefaultServlet.class,"/*");
holder.setInitParameter("resourceBase","bin");
holder.setInitParameter("pathInfoOnly","true");
// Serve some hello world servlets
context.addServlet(MyServlet.class,"/*");
See the embedded example for a more complete example of 1 Servlet + 1 DefaultServlet.
http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java?h=jetty-8
Just be sure your resourceBase init parameter points to the path where your class files are.

Related

Embedded jetty 9 doesn't work for #Webservlet

I'm using java 11 and embedded jetty 9 foor my javaEE application,I'm trying to use #Websevlet annotation to publish my servlet but it doesn't work i don't know why.
My start class java
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.*;
public class Start {
public static void main(String[] args) throws Exception {
Server server = new Server(80);
WebAppContext wacHandler = new WebAppContext();
wacHandler.setConfigurations(new Configuration[]
{
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new JettyWebXmlConfiguration()
});
server.setHandler(wacHandler);
server.start();
server.join();
}
}
My hello world class
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet( "/getservlet")
public class ServletX extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hi there..</h1>");
}
}
I don't have a web.xml configuration ,Should i do?
If ServletX is in the war file, meaning it's in WEB-INF/classes/ archive directory, then the configuration you have declared (specifically the AnnotationConfiguration) will perform a bytecode scan of the WAR file and load the #WebServlet annotation.
Also note that the WebAppContext will need point to this WAR file, which your code examples do not do.
WebAppContext wacHandler = new WebAppContext();
waxHandler.setWar("/path/to/myapp.war");
// ... more setup
But! if the ServletX is not in the WAR file, but is instead housed with your embedded-jetty Start class, then you'll need to expose the servlet container to be scanned by the bytecode scanning step.
You can always turn on DEBUG/FINE level logging for the named logger org.eclipse.jetty and see the activity being performed with regards to the deployment and bytecode scanning.

How to set the HTTP-Session-Timeout in Jetty 9 (embedded)?

I would like to use Jetty 9 (v9.2.12.v20150709) embedded for my test cases.
But I am unable to change the HTTP-Session-Timeout programmatically.
This call webapp.getSessionHandler().getSessionManager().setMaxInactiveInterval(timeoutInSeconds); doesn't seem to work.
Here is reduced code segement, which shows what I do:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
#SuppressWarnings("javadoc")
public class EmbeddedJetty
{
#SuppressWarnings("serial")
public static class TimeoutServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
// return the value of the currently used HTTP-Session Timeout
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>Timeout: " + request.getSession()
.getMaxInactiveInterval() + "</h1>");
}
}
public static void main(String[] args) throws Exception
{
// the custom timeout, which I am trying to set
int timeoutInSeconds = 1234;
Server server = new Server(0);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setResourceBase(System.getProperty("user.dir"));
// Can't set custom timeout. Following Statement doesn't work.
webapp.getSessionHandler().getSessionManager().setMaxInactiveInterval(
timeoutInSeconds);
server.setHandler(webapp);
webapp.addServlet(TimeoutServlet.class.getName(), "/*");
server.start();
// get current URL of the server
String url = server.getURI().toString();
System.out.println("\n URL: " + url);
// server.dumpStdErr();
// make a request to get the used timeout setting
HttpClient httpClient = new HttpClient();
httpClient.start();
ContentResponse response = httpClient.GET(url);
httpClient.stop();
String timeoutInfo = response.getContentAsString();
System.out.println(timeoutInfo);
// check if the custom timeout is used
if( timeoutInfo.contains(String.valueOf(timeoutInSeconds)) )
{
System.out.println("Custom Timeout is used.");
}
else
{
// Unfortunately, I get the default(?) everytime
System.out.println("Default Timeout? Custom Value is NOT used.");
}
System.out.println("Press Enter to exit ...");
System.in.read();
server.stop();
server.join();
}
}
I am using the WebAppContext-Style of setup, because this allowed me to get my ServletContextListeners to work by using WebAppContext.addEventListener(). Which I couldn't get to work by using a ServletHandler.
Also I am using the Version 9.2.12.v20150709 of Jetty, because it is Classpath-compatible with Selenium v2.5.2 (which supports Java 7 (project requirement)).
Have you any suggestions, what i am doing wrong?
Thank you for your time.
A WebAppContext has some defaults, which are loaded during server.start() (WebAppContext.startContext()).
These defaults contain also a DefaultWebDescriptor located in the jetty-webapp.jar under /org/eclipse/jetty/webapp/webdefault.xml. This Descriptor includes a session-config, which sets the timeout to the default of 30m (1800s).
To overwrite the defaults the call of setMaxInactiveInterval() must be done after the server is started:
server.start();
webapp.getSessionHandler().getSessionManager().setMaxInactiveInterval(timeoutInSeconds);
Or to avoid these defaults, it might be better to use a ServletContextHandler instead.

How to integrate Xlloop within JAVA web server?

I am trying to integrate XLLoop from a servlet and trying to run in via HTTP protocol. Below is my code:
XlloopServlet.java
#WebServlet(value = "/FunctionServer", name = "FunctionServer", asyncSupported = true)
public class XlloopServlet extends FunctionServlet {
private static final long serialVersionUID = -3845895326255874126L;
#Override
public void init(final ServletConfig config) throws ServletException {
// Create a function information handler to register our functions
FunctionInformationHandler infoHandler = new FunctionInformationHandler();
// Create a reflection function handler and add the required methods
FunctionHandler handler = new FunctionHandler();
infoHandler.add(handler.getFunctions());
// Set the handlers
CompositeFunctionHandler compositeHandler = new CompositeFunctionHandler();
compositeHandler.add(handler);
compositeHandler.add(infoHandler);
// Setting the function handler in the parent servlet
setHandler(compositeHandler);
}
and my FunctionHandler class which registers the functions:
public class FunctionHandler implements IFunctionHandler, FunctionProvider {
private ReflectFunctionHandler rfh;
public FunctionHandler() {
// Create a reflection function handler and add the Math methods
rfh = new ReflectFunctionHandler();
rfh.addMethods("Math.", Math.class);
rfh.addMethods("Math.", Maths.class);
rfh.addMethods("CSV.", CSV.class);
rfh.addMethods("Reflect.", Reflect.class);
}
#Override
public XLoper execute(IFunctionContext arg0, String arg1, XLoper[] arg2) throws RequestException {
return rfh.execute(arg0, arg1, arg2);
}
#Override
public boolean hasFunction(String arg0) {
return rfh.hasFunction(arg0);
}
#Override
public FunctionInformation[] getFunctions() {
return rfh.getFunctions();
}
public ReflectFunctionHandler getReflectFunctionHandler() {
return rfh;
}
}
My XLLoop ini file is as below:
protocol=http
url=http://localhost:8080/MyApp/FunctionServer
Now, when I try to call a function from my excel, I get a call in the servlet class and everything executes, but functions are not getting executed on the excel file.
Anyone having any idea about how to integrate XLLoop plugin on a webserver like tomcat?
I've just implemented this with JAX-RS and a bit of Spring. I use a REST endpoint to populate the xlloop.ini file with the correct server host/port for the running service and then package up my xlsb, xll and ini file in a zip for clients to download. It's not particularly pretty at the moment but the web.xml and Startup snippets are below.
The thing I haven't spent time on yet is memory management. If a lot of users load a lot of data, I'll need to periodically clean that up, so beware of idle session threads!
Web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>com.myapp.web.excel.XLLoopStartup</listener-class>
</listener>
XLLoopStartup.java
public class XLLoopStartup implements ServletContextListener {
public static XLLoopStartup INSTANCE;
private FunctionServer fs;
#Inject
private SomeInjectionThing usefulSpringStuff;
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
#Override
public void contextInitialized(ServletContextEvent sce) {
INSTANCE = this;
// Initialize my Spring stuff
if (sce != null){
WebApplicationContextUtils//
.getRequiredWebApplicationContext(sce.getServletContext())//
.getAutowireCapableBeanFactory()//
.autowireBean(this);
}
Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
registerConverters();
fs = new FunctionServer(Integer.parseInt(System.getProperty("port.tomcat.xlloop", "10606")));
ReflectFunctionHandler rfh = new ReflectFunctionHandler();
rfh.addMethods(ExcelTrades.CATEGORY, ExcelTrades.class);
rfh.addMethods(ExcelUtils.CATEGORY, ExcelUtils.class);
rfh.addMethods(ExcelPositions.CATEGORY, ExcelPositions.class);
rfh.addMethods(ExcelProducts.CATEGORY, ExcelProducts.class);
// Create a function information handler to register our functions
FunctionInformationHandler firh = new FunctionInformationHandler();
firh.add(rfh.getFunctions());
// Set the handlers
CompositeFunctionHandler cfh = new CompositeFunctionHandler();
cfh.add(rfh);
cfh.add(firh);
DebugFunctionHandler debugFunctionHandler = new DebugFunctionHandler(cfh);
fs.setFunctionHandler(new SecureFunctionHandler(debugFunctionHandler));
try {
fs.run();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
// For quick testing
public static void main(String[] args) {
new XLLoopStartup().contextInitialized(null);
}
// Function classes can statically access this instance and get spring things from it
public SomeInjectionThing getThing() {
return usefulSpringStuff;
}
}
ExcelService.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.io.IOUtils;
import io.swagger.annotations.Api;
#Api("excel")
#Path("/excel")
public class ExcelService {
#Context
UriInfo uri;
#GET
#Path("/download")
#Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response download() {
StringWriter sw = new StringWriter();
// Create an INI file. We should probably store all default settings in a file and just add the server info to
// it.
sw.write("server=");
sw.write(uri.getBaseUri().getHost());
sw.write(":");
sw.write(System.getProperty("port.tomcat.xlloop", "10605"));
String inifile = sw.toString();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
// Add the ini file to the zip
ZipEntry entry = new ZipEntry("xlloop.ini");
zos.putNextEntry(entry);
zos.write(inifile.getBytes());
zos.closeEntry();
// Add the Excel files
writeFileFromClasspath(zos, "xlloop.xll");
// This is my custom Excel macro sheet with other useful functions for user authentication etc.
writeFileFromClasspath(zos, "xlloop.xlsb");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return Response.ok(new ByteArrayInputStream(baos.toByteArray()))
.header("Content-Disposition", "attachment; filename=xlloop.zip").build();
}
private void writeFileFromClasspath(ZipOutputStream zos, String filename) throws IOException {
ZipEntry xlFileEntry = new ZipEntry(filename);
zos.putNextEntry(xlFileEntry);
zos.write(IOUtils.toByteArray(ExcelService.class.getClassLoader().getResourceAsStream(filename)));
zos.closeEntry();
}
}

How to run a java web application?

I have a folder that has only .java files. There are no .html, .jsp, .jsf etc. files only .java. I was told that this is a web application, but I have no idea on how to run it.
Here is a sample code from one of the .java files:
public List<String> generateHtml(String name, String css) {
List<String> html = new ArrayList<>();
html.add("<!DOCTYPE HTML><html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + css
+ "\"/></head><body>");
html.add("<div class='screen page_size " + name + "'>");
for (HtmlElement element : orderedElements) {
element.generateHtml(html);
}
html.add("</div>");
html.add("</body></html>");
return html;
}
I tried making a web project in eclipse and importing the files and running it, but no luck. It gives me a lot of errors with something to do with jetty. After installing jetty it still didnt work. Maybe I am installing it wrong. Anyone has any idea?
If you want to create a runnable war with jetty, have a look a the Embedded Jetty examples
You can call the generateHtml method from the servlet below.
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
server.start();
server.join();
}
#SuppressWarnings("serial")
public static class HelloServlet extends HttpServlet
{
#Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
//From here you can call the generateHtml method
response.getWriter().println("<h1>Hello from HelloServlet</h1>");
}
}
}

Jetty 9 (embedded): Adding handlers during runtime

Is there any way to add handlers to a running embedded Jetty instance? We have migrated an old Jetty 6 based project to Jetty 9 and we need for our plugin system the possibility add and remove dynamically handlers...
See the example below...
Server server = new Server();
[...]
server.start();
[...]
Handler[] existingHandler = server.getHandlers();
// There is no more
server.addHandler(newHandler);
// only this you can do, but only if the server is stopped
server.setHandler(newHandler)
Note: newHandler is a HandlerCollection...
Here a complete code sample. Next to using HandlerCollection(true), it is also important to start the new context handler explicitly.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
public class DynamicContextHandlers {
public static void main(String[] args) throws Exception {
new DynamicContextHandlers().run();
}
public void run() throws Exception {
int port = 8080;
Server server = new Server(port);
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/hello");
contextHandler.setResourceBase(".");
contextHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
contextHandler.setHandler(new HelloHandler(""));
HandlerCollection contextHandlerCollection = new HandlerCollection(true); // important! use parameter
// mutableWhenRunning==true
// add context handler before starting server (started implicitly)
contextHandlerCollection.addHandler(contextHandler);
server.setHandler(contextHandlerCollection);
server.start();
System.out.println("Server started at port " + port + " with context handler for /hello");
System.out.println("Press enter to add context handler for /hello2");
System.in.read();
ContextHandler contextHandler2 = new ContextHandler();
contextHandler2.setContextPath("/hello2");
contextHandler2.setResourceBase(".");
contextHandler2.setClassLoader(Thread.currentThread().getContextClassLoader());
contextHandler2.setHandler(new HelloHandler("2"));
// add handler after starting server.
contextHandlerCollection.addHandler(contextHandler2);
// important! start context explicitly.
contextHandler2.start();
System.out.println("Press enter to exit.");
System.in.read();
server.stop();
}
public class HelloHandler extends AbstractHandler {
String string;
public HelloHandler(String string) {
this.string = string;
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Hello World" + string + "</h1>");
}
}
}
With Jetty 9.1.0.v20131115 you can use the mutableWhenRunning flag on HandlerCollection constructor ...
HandlerCollection coll = new HandlerCollection(true);
This will ignore the isStarted() tests on the collection itself during .setHandlers(Handlers[]) and .addHandler(Handler) calls.
This behavior is only available for the HandlerCollection itself, you can add individual handlers, or set the entire handler tree without regards to the LifeCycle of the HandlerCollection.
Eg:
Server server = new Server(8080);
HandlerCollection myhandlers = new HandlerCollection(true);
server.setHandler(myhandlers);
// add some initial handlers
myhandlers.setHandlers(new Handlers[] { helloHandler, indexHandler });
// start server
server.start();
// ... at some point later, during runtime
FooHandler fooHandler = new FooHandler();
fooHandler.start();
myhandlers.addHandler(fooHandler);
BarHandler barHandler = new BarHandler();
barHandler.start();
myhandlers.addHandler(barHandler);

Categories