Reputation:
Programming a website with PHP is very easy as it always gives back an HTML response which the browser can send to the user. But how to release a website with java? I'm using Aruba.it hosting, I created a file containing java code, actually a simple servlet with this code;
import java.io.IOException;
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("/Demo")
public class Demo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("Do get called");;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("Do post called");
}
}
However, when I visit www.mywebsite.com/Demo.java or simply /Demo, I get the code I showed you before;
I know this is a very stupid question, but I have no idea what to do. When I run a PHP file everything works as expected. What would you do?
Upvotes: 1
Views: 1208
Reputation: 1086
What you are asking is indeed a beginner question. Most webhosting providers (like aruba.it) base their Linux hosting services on Apache httpd server (better known as just Apache) which is a web container and supports php out of the box. However Java servlets need a servlet container like Apache Tomcat. For setting up a servlet container you need to have a VPS rather than a shared Linux hosting.
Secondly the code you have provided is actually a servlet which needs more elaborate steps and configuration to deploy. Please see this tutorial https://www.tutorialspoint.com/servlets/servlets-packaging.htm
If you are looking for something similar to PHP then consider using JSP (Java server pages) which allow you to embed html. Even so JSP still requires a servlet container like Tomcat to deploy (https://www.codejava.net/servers/tomcat/how-to-deploy-a-java-web-application-on-tomcat). Just that once initial set up is done, with JSP you can just put them in the correct location and call them like a php page and expect them to get compiled and run automatically rather than going through the more elaborate steps for setting up a servlet
Upvotes: 2