HTTP Status 404 - Servlet .... is not available - servlets

I use eclise to create a servlet like this :
package hello;
public class NewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
String name = request.getParameter("textField");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<html><head></head><body><center>");
pw.print("Hello " + name + "!");
pw.print("</center></body></html>");
}
}
and a html file like :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="NewServlet">
<p align="center">
<font>Input some text</font> <br> <input type="text"
name="textFiled"> <br> <input type="submit"
value="submit"> <br>
</p>
</form>
</body>
</html>
when i run the servlet, met an error :
HTTP Status 404 - Servlet NewServlet is not available
--------------------------------------------------------------------------------
type Status report
message Servlet NewServlet is not available
description The requested resource (Servlet NewServlet is not available) is not available.
i checked the folder : WEB-INF or any folder else and can't see file .class
How is this caused and how can I solve it?

You should check web-inf folder in your IDE and map your servlet in web.xml file
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
make sure that this mapping is done properly and also your servlet is not in any package or folder if so then in servlet tag write that class name followed by . and your servlet name.
If problem still arises just make sure that you delete that .class file of your servlet and build your project again.(Net beans have an option of clean and build and then run) haven't use eclipse but i am sure it has similar option as well

Servlets needs to be registered and mapped on a specific URL pattern in order to be able to execute them by a HTTP request. Given your HTML code you seem to expect the servlet to listen on an URL of /NewServlet.
If you're using Tomcat 7, then just put the #WebServlet annotation on the class with exactly that URL pattern:
#WebServlet("/NewServlet")
public class NewServlet extends HttpServlet {
// ...
}
If you're still on Tomcat 6 or older for some reason, then you'd need to do it by the old fashioned web.xml way. A concrete example can be found in our servlets wiki page.
Eclipse won't show .class files in the project explorer. It will only show them in the navigator, in the /build folder. But this should not be something to worry about right now.

Format in web.xml should be like this.
<servlet-name>NewServlet</servlet-name>
<servlet-class>PackageName.JavaClass</servlet-class>
which in your case is
<servlet-name>NewServlet</servlet-name>
<servlet-class>Hello.NewServlet</servlet-class>

edite this:
form method="post" action="NewServlet"
to this
form method="post" action="/(your project name ) /NewServlet"
i had the same problem and this worked for me

Related

How to connect properly my servlet with my post form? [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I am learning java maven project, and i just want to know how i can properly connect my post form with my servlet when i submit the form.
i tried to search but can't get the right answer that i need.
I'm working with eclipse and this my folder organization!
this is my servlet:
package servlet;
import java.io.IOException;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet(name="Init")
public class Init extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
/*Creation et initialisation du message */
//creation de la session
HttpSession session=request.getSession();
//pseudo user
String name=request.getParameter("pseudo");
session.setAttribute("usersession", name);
//redirection après application du servlet INIT
this.getServletContext().getRequestDispatcher("/interface.jsp").forward(request, response);
}
}
this is my web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Init</servlet-name>
<servlet-class>src.main.java.servlet.Init</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Init</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
this is my index.jsp which contains my form:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Chatons !</title>
</head>
<body>
<h1>Bienvenue sur Chatons.org</h1>
<form method="post" action="/java/servlet/Init">
<p>
Entrez votre pseudo :
<input type="text" name="pseudo">
<input type="submit" value="Connexion">
</p>
</form>
</body>
Annotation (#WebServlet in your case) represents the metadata. If you use annotation, web.xml file (deployment descriptor) is not required but you should have Tomcat 7 as it will not run in previous versions of Tomcat server. #WebServlet annotation is used to map the servlet with the specified name.
The web application deployment descriptor web.xml has become optional in Servlet 3.0. Instead, the container at run time will process the annotations of the classes in WEB-INF/classes.
Use #WebServlet(value="/init") instead of yours with the 'name' and get rid of your web.xml descriptor if you prefer annotations.
If you have your src/servlet/Init.java this class is compiled and it will be stored as .class in the following hierarchy:
build/classes/servlet/Init.class
When the container sees the annotation above the class-definition it will check for the .class file in the specified folder and it resolves the call for the required Servlet.
If you have the <form action="init" method="post"> when you hit the submit button the container then searches for the url pattern in the annotation and rest works as said before.
For servlet 3.0 api you don't need a web.xml, you can use annotations instead, have you corrected the action in html

Unable to serve static resources with spring, receive index instead

I have a simple Spring web application.
#Controller
public class GreetingController {
#Autowired
GreetingRepository repository;
#GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
#PostMapping("/greeting")
public String greetingSubmit(#ModelAttribute Greeting greeting) {
repository.save(greeting);
return "result";
}
}
The HTML is:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/greeting}" th:object="${greeting}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
This is the css file that is referenced in the HTML:
p {
color: #ff5588;
}
However, the css is not applied.
In fact, when I query localhost:8080/css/style.css it returns the HTML content of the index page.
It might be a security configuration issue. Is there a security implementation (SpringSecurity or custom) on your project? If so, does your user have access to /css/* url or this url has public access? The redirection might be occur if user doesn't have access to url or there is an exception while processing request.
The security configuration turned out to be blocking all requests to resources. In stead, it was redirecting those requests to the index page (which was configured).
The solution turned out to be simple, authorize all requests to the resources of the website (/images/** and /css/** and /js/**).
Once that was configured, the web-application worked as expected.

Error while moving HTML form from jsp to ThymeLeaf

I am trying to follow this as reference Serving Static content in SpringBoot
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;
/**
* Created by Eric on 11/25/2015.
*/
#org.springframework.stereotype.Controller
public class Controller {
#RequestMapping("/appPage")
public String greeting(#RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("title", "Best Of the App");
model.addAttribute("basecontext", "Best Of the App");
return "appPage";
}
}
My HTML form being below
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
<input type="hidden" type="text" id="basecontext" value='${basecontext}'/>
</body>
</html>
I am trying to set value in hidden input field. But that gives me error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Exception parsing document: template="appPage", line 9 - column 33
I am trying to move this html page which was getting loaded in a JSP application to Spring Boot + ThymeLeaf.
If I simply place this content in index.html without a Context handler in Controller. the page is loaded just fine. Thymeleaf does not throw any error.
ThymeLeaf uses xml and not html and you are not allowed to have attributes of the same name in xml type="hidden" type="text"
You actually should get SAXParseException: Attribute "type" was already specified for element in your spring log

Java Servlet 404 error

My system has Tomcat seven and all the files are under webapps. The file structure is
webapps/ WelcomeForm/ web/ WelcomeForm.html
WEB-INF/ web.xml
lib/ classes/ hello/ HelloWorldServlet.java HelloWorldServlet.class
The web folder holds WelcomeForm.html.
WEB-INF holds the web.xml.
lib holds servlet-api.jar and
classes holds HelloWorldServlet.java.
the html file runs fine but I cannot run the Java file as it returns the message:
HTTP Status 404 - /hello
type Status report
message /hello
description The requested resource (/hello) is not available.
The code for the files is below:
WelcomeForm.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="/hello">
<font size="10" color="red">Hello World!</font><BR>
Type your first name and click submit button <input TYPE=TEXT NAME="username" SIZE=20>
<P><input type="submit" value="Submit">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>hello.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
HelloWorldServlet.java
package hello;
import java.io.IOException;
import javax.servlet.ServletException;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("username");
PrintWriter out = response.getWriter();
out.write("Your Name is :" );
out.print(name);
}
}
What am I doing wrong?
Check browser URL. You are missing context.
Let Say, You are running at http://localhost:8080/test/index.jsp where test is your context path.
So, When calling Servlet It should be like http://localhost:8080/test/hello.
In your case, Its not like that.
So, Adding cotextpath will solve your problem.
e.g. action="<%=request.getContextPath()%>/hello"
OR you can use
e.g. action="hello"
So, When you add "/" to action always add context path.

Spring MVC Static Resources partially work

I have a basic directory app that works fine except that it seems to only sometimes find the static resources that I’ve configured using the mvc:resources tag. My search of the board found problems related to handler mappings, but my problem seems to be different.
Specifically, when the PersonController is called via a method mapping to “/person”, it returns personlist.jsp using the view resolver and correctly finds and uses the static css and js files. No problems.
When the same controller is called via another method mapping to “/person/{familyid}” ( narrows the person list to a particular family), it returns the same personlist.jsp…but now it fails to find or use the css and js files (though it does display the correct data).
I don’t understand why there is a behavior difference since both scenarios use the same Controller, the same return String (return “personlist”), and resolve to the same JSP (ie. with the same Head section links for the css, js).
I looked at what came back in the browser for each case using ‘view source’, and both pages return the same head tag rendering for the css and js linking:
<link href="resources/css/directory.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript" src="resources/scripts/jquery-1.7.min.js"></script>
<script type="text/javascript" src="resources/scripts/directory.js"></script>
I thought the problem could be with my tag mapping, so I also tried this:
<resources mapping="**/resources/**" and
resources mapping="resources/**"
but no help.
Am I approaching the use of static resources properly here (and what is the right resources tag mapping if that’s the problem)? Thanks.
I am using Spring 3.0.6 and my css and js files are located under /WebContent/resources/css and /WebContent/resources/scripts respectively, which are mapped using the mvc:resource tag (see below).
PersonController:
#Controller
public class PersonController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
List<Person> personList;
Boolean familyCalled = false;
#Autowired
PersonService personService;
#RequestMapping(value="/people", method=RequestMethod.GET)
public String people(Model model) {
logger.debug("Received request to show peoplelist page");
System.out.println("Running inside people() method of PersonController");
personList = personService.getPersons();
familyCalled = false;
model.addAttribute("personList", personList);
return "personlist";
}
#RequestMapping(value="/people/{familyId}", method=RequestMethod.GET)
public String familyMembers(#PathVariable("familyId") String fid, Model model) {
System.out.println("Running inside familyMembers() method of PersonController");
personList = personService.getPersonsInFamily(fid);
familyCalled = true;
model.addAttribute("personList", personList);
return "personlist";
}
Servlet-Context.xml (without namespaces):
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- for transactions -->
<tx:annotation-driven/>
<!-- Needed for #PreAuthorize security on methods -->
<aop:aspectj-autoproxy/>
<context:annotation-config />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="resources/" />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven/>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.c3works.preps" />
</beans:beans>
personlist.jsp (Head section):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</meta>
<title>XXXXXXXXXXXXXXXXXXX</title>
<link href="resources/css/directory.css" rel="stylesheet" type="text/css">
</link>
<script type="text/javascript" src="resources/scripts/jquery-1.7.min.js">
</script>
<script type="text/javascript" src="resources/scripts/directory.js">
</script>
</head>
Your URLs are relative and therefore the browser is looking for the resources in the wrong place. (Check the resulting HTML code)
One solution is to use the <spring:url> tag to build the urls of the resources.
<spring:url var="banner" value="/resources/images/banner-graphic.png" />
<img src="${banner}" />

Resources