JSP Servlet URL patterns

Viewed 46

I've created a Java web app (EE 8) that runs on the tomcat 10 server but doesn't work with URL(href link) in an index.JSP page; I haven't changed anything in the generated application. but throws 404 code in the "http://localhost:8080/hello-servlet" url. how to map URL with @webSevlet annotations.

 @WebServlet(name = "helloServlet", value = "/hello-servlet")
 public class HelloServlet extends HttpServlet {
private String message;

public void init() {
    message = "Hello World!";
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException 
   {
    response.setContentType("text/html");

    // Hello
    System.out.println("Get Requests");
    PrintWriter out = response.getWriter();
    out.println("<html><body>");
    out.println("<h1>" + message + "</h1>");
    out.println("</body></html>");
   }

public void destroy() {
   }
}
1 Answers

Including the project name might solve this. The structure of your URL should look like this: http://localhost:8080/myProjectName/hello-servlet. This is caused by tomcat, because it can host multible applications on one server and you probably did not upload it as default application.


You can find your project name in the web.xml:

<display-name>myProjectName</display-name>


Loads with status 200: enter image description here


If any file of yours is working you can use this code to list all active servlets:

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Map"%>
<%
String jspUrl = request.getRequestURL().toString(); //the url of the current file
String[] parts = jspUrl.split("/");
String parentUrl = jspUrl.replace(parts[parts.length - 1], ""); //removes the file name
out.print(jspUrl + "<br>->" + parentUrl + "<br>List of all servlets: <br>");
Map<String, ? extends ServletRegistration> servletRegistrations = request.getServletContext().getServletRegistrations();
for (String servlet : servletRegistrations.keySet()) { //Loops trough every registered servlet
    ServletRegistration registration = servletRegistrations.get(servlet);
    String servletValue = new ArrayList<String>(registration.getMappings()).get(0); //get the first mapping
    String url = parentUrl + servletValue.replaceFirst("/", "");
    out.print("- " + servlet + ": <a href=\"" + url + "\">" + servletValue + "</a><br>");
}
%><br>

The output looks something like this and includes the URLs (clickable) to the listet sites:

http://localhost:8080/myProject/index.jsp
->http://localhost:8080/myProject/
List of all servlets:
- [...]
- default: /
- jsp: *.jspx
- helloServlet: /hello-servlet
- [...]
Related