Error HTTP Status 404. The requested resource is not available. [Netbeans] - java

I do a project Fahrenheit to Celsius conversion using netbeans with Tomcat 8.0.37
when i try to run project, i get a issue HTTP Satus 404.
My index.html
<html>
<head>
</head>
<body>
<h3>Please enter Fahrenheit temperature:</h3><p>
<form action="/conv/test">
Temperature(F) : <input type="text" name="temperature"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
My web.xml
<web-app>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>doGetMethod.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
My TestServlet.java
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException
{
String temperature = req.getParameter("temperature");
DecimalFormat twoDigits = new DecimalFormat("0.00");
try
{
double tempF = Double.parseDouble(temperature);
String tempC = twoDigits.format((tempF -32)*5.0/9.0);
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<h3>" + temperature + " Fahrenheit is
converted to " + tempC + " Celsius</h3><p>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"There was an input error");
}
}
}
Please help me to solve this issue !
I apologize for not being word-perfect in English.

You should access the index.html at localhost:8080/contextRoot/index.html. The action associated to the form should map to the servlet, so it should be action="/test". The servlet-class tag in the web.xml should specify your servlet class full name such as mypackage.TestServlet. You could avoid using a web.xml and save you some time by using annotation on the Servlet class as well explained here https://docs.oracle.com/javaee/7/tutorial/servlets004.htm#BNAFU. Also look here for a similar example https://stackoverflow.com/a/2395262/6848537

Related

404 error with java servlets. can't see html file

I am following derek banas' tutorial on youtube (https://www.youtube.com/watch?v=_HnJ501VK3M) and when I try to run the code the browser displays a status-404 and
Message: /Lesson41/
Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I was getting IllegalArguementsException saying something about 2 different servlets being mapped to the same url-pattern. So I removed the #WebServlet annotation.
Now I'm getting the 404 and I don't know what the cause is. I think eclipse doesn't see the sayhello.html
Here is the code:
Servlet: Lesson41.java
public class Lesson41 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String usersName= request.getParameter("yourname");
String theLang = request.getParameter("Language");
int firstNum = Integer.parseInt(request.getParameter("firstnum"));
int secondNum = Integer.parseInt(request.getParameter("secondnum"));
int sumONum = firstNum + secondNum;
response.setContentType("text/html");
PrintWriter output = response.getWriter();
output.println("<html><body><h3>Hello " + usersName);
output.println("</h3><br />" + firstNum + " + " + secondNum);
output.println(" = " + sumONum + "<br />Speaks " + theLang);
output.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>Lesson41</servlet-name>
<servlet-class>helloservlets.Lesson41</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Lesson41</servlet-name>
<url-pattern>/Lesson41</url-pattern>
</servlet-mapping>
</web-app>
html: sayhello.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<form method="post" action="http://localhost:8080/Lesson41/">
What's your name?<br />
<input name="yourname" /><br />
First Number<br />
<input name="firstnum" /><br />
Second Number<br />
<input name="secondnum" /><br />
<input type="hidden" name="Language" value="English" /><br />
<input type="submit" />
</form>
</body>
</html>
The directory structure:
directory Structure
Expected Output:
It should show a form with fields for name, number1, number2 and a submit button. It correctly goes to localhost:8080/Lesson41/ but can't see the html.
Update the url-pattern to /Lesson41/
<url-pattern>/Lesson41/</url-pattern>
form action change to /Lesson41/ and try. might help you.
<form method="post" action="/Lesson41/">
</form>
Also, while mapping you are using servlet-class as 'helloservlets.Lesson41', need to add the package. 'helloservlets' in servlet 'Lesson41'.

Getting more information about an object when clicking on a text in html using MVC

So I'm a making a small web app to get information about games, I have made a searchBar that request the search to an API and then I get the first 10 games with the most similar title to the search. But I only show the title.
This is an example of a search
The games have a lot of attributes, one of them is the ID, and it allows me to get all the info of a game using a controller.
Right now the app works like this:
1: You search the title of a game
2. A controller gives me a List of IDs and with the ids I get the rest of the info about the games, but I only show the titles.
Now, what I want to do:
3.When you click on a title you use a controller, and from the ID it request (again, I'm not sure if I can use the previous games objects) all the info from that game and Shows it.
The controllers works fine, but I'm having problems with the HTML.
This is the controller for the search:
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("searchQuery");
RequestDispatcher rd = null;
log.log(Level.FINE, "Searching for games that contain " + query);
GameResource game = new GameResource();
GameSearch[] gameResults = null;
gameResults = game.getGameSearch(query);
//System.out.println(Arrays.toString(gameResults));
List<Game> listaBusqueda = new ArrayList<Game>();
if (gameResults.length!=0){
rd = request.getRequestDispatcher("/success.jsp");
for (GameSearch g : gameResults) {
listaBusqueda.add(game.getGame(g.getId().toString()));
}
request.setAttribute("games", listaBusqueda);
} else {
log.log(Level.SEVERE, "Game object: " + gameResults);
rd = request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
...
This is the controllers that gives me a game using an ID
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gameId = request.getParameter("id");
GameResource resource = new GameResource();
RequestDispatcher rd = null;
log.log(Level.FINE, "Retrieving game");
Game game = resource.getGame(gameId);
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Both of them works, in the last one the objects are created correctly and the ID is obtained.
Now, this is the html for success.jsp, and this is where the problem is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Search results</title>
</head>
<body>
<fieldset id="IGDB">
<legend>
IGDB search for
<c:out value="${param.searchQuery}" />
</legend>
<c:forEach items="${requestScope.games}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<a href="GameIdController?id=${game.id}"><c:out value="${game.name}"
/></a>
<br />
</c:forEach>
</fieldset>
<c:if test="${requestScope.Item=='gameID' }">
<c:forEach items="${requestScope.Game}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<c:out value="${game.name}" />
<br />
</c:forEach>
$game = ${requestScope.Game}
<c:out value="${game.name}"/>
</c:if>
<article name = "gameByIDArticle" id = "gameByIDArticle">
</article>
</body>
</html>
When I click in a title, I get redirected to a blank webpage (http://localhost:8090/GameIdController?id=IdOfTheGame),as you can see the id is included in the URL, but it's completely blank and it should include the title again as is stated in my code.
I will also include my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<description></description>
<display-name>GameSearchController</display-name>
<servlet-name>GameSearchController</servlet-name>
<servlet-class>aiss.controller.GameSearchController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameSearchController</servlet-name>
<url-pattern>/GameSearchController</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>GamePopularityController</display-name>
<servlet-name>GamePopularityController</servlet-name>
<servlet-class>aiss.controller.GamePopularityController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GamePopularityController</servlet-name>
<url-pattern>/GamePopularityController</url-pattern>
</servlet-mapping>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/api</param-value>
</context-param>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-
class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-
class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>aiss.api.GameApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>GameIdController</display-name>
<servlet-name>GameIdController</servlet-name>
<servlet-class>aiss.controller.GameIdController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameIdController</servlet-name>
<url-pattern>/GameIdController</url-pattern>
</servlet-mapping>
</web-app>
Okay i think i understand why you are seeing a blank page. Everything is working as expected, the problem seems to be with this:
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
The reason why you are seeing a blank page is because your game variable is not null. And you don't have a forward statement in the first part of that if else block.
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
rd.forward(request, response); // missing this!
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
EDIT: In response to your other problem from the comment, i think the forEach is having problems because of this:
<c:forEach items="${requestScope.Game}" var="game">
change it to this:
<c:forEach items="${Game}" var="game">

Why does my servlet request.getParameter return null?

I'm having a problem with the request. It always returns "null", but I don't know why. I want it to return a name.
This is my servlet:
public class MinServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Syvtabellen - fra en servlet</title></head>");
out.println("<body>");
out.println("<p>Her er syv-tabellen:<br>");
for (int i=1; i<=10; i++)
{
out.println("Syv gange "+ i +" er: "+ 7*i +".<br>");
}
out.println("</body>");
out.println("</html>");
String parameterværdi = request.getParameter("navn");
out.print( "Værdien af parameteren 'navn' er: <br>" + parameterværdi );
}
}
This is the index.xml:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
</body>
This is the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>MinServlet</servlet-name>
<servlet-class>konti.MinServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MinServlet</servlet-name>
<url-pattern>/MinServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Do I've to add it in the index.xml somehow? I know that the parameter returns null if the parameter doesn't exist, but I don't know how to fix it :)
I believe you are following a tutorial. As Elliott said in his comment you need to have a parameter called "navn" in you view to catch it from your servelet otherwise you will get a null. Or else there should be a query string called "navn". Here I can't see any parameter called "navn" in your client side.
For example: http://www.java4s.com/java-servlet-tutorials/example-of-request-getparameter-retrieve-parameters-from-html-form/
According to your code:
index.html
<font face="verdana" size="2px">
<form action="getVal" method="post">
First way to pass request Param <input type="text" name="navn"><br>
<input type="submit" value="Submit">
</form>
</font>
TestApp.java
public class TestApp extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String n1=req.getParameter("navn");
pw.println("Requested Value" +n1);
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>sumOfTwoNumbers</servlet-name>
<servlet-class>java4s.OngetParameter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestApp</servlet-name>
<url-pattern>/getVal</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Or else you can pass query string as following
Second way to pass Request param:
index.html
Click here

Jsp servlet - login page is not redirecting properly

I am trying to create a login service but my pages are not redirecting properly. I have following:
login.jsp
<form action="login" method="post">
User Name
<br>
<input type="text" name="userId"/>
<br><br>
Password
<br>
<input type="password" name="password"/>
<br><br>
<input type="submit"/>
</form>
LoginServlet.java
package org.sohail.javabrains;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId, password;
userId=request.getParameter("userId");
password=request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if (result) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java - has a authenticate(userId, password) method which connects to database, verifies userId and pass and returns a boolean value.
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.sohail.javabrains.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
from login.jsp page, doesn't matter what I put I get following error:
HTTP Status 404 - /LoginApp/login
It should redirect the page to success.jsp if authenticate() reutrns true.
I am pretty new to this so please feel free to provide any other suggestions.
Thank you Birgit Martinelle for following answer:
change your web.xml servlet mapping to
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and remove the WEB-INF part from your redirect url:
RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
– Birgit Martinelle 50 mins ago

Executing MySQL Commands from a Java Servlet

I'm trying to get my servlet to output the results of SQL commands entered by the user. Right now, the servlet correctly detects when a command does not include "SELECT", "INSERT", or "DELETE", and outputs an error message. When the command is valid, nothing is outputted. I know this means my problem is likely occurring either where I am trying to connect to the database, or where I am trying to print output to "out".
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<xml version = \"1.0\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns = \"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>MySQL Servlet</title>");
out.println("<style type='text/css'>");
out.println("body{background-color: blue}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
String query = request.getParameter("query");
if (query.toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.printf("%20s\t", metaData.getColumnName(i));
}
out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.printf("%20s\t", resultSet.getObject(i));
}
out.println();
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query).executeUpdate(query);
out.println("\t\t Database has been updated!");
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out.println("\t\t Not a valid command or query!");
}
out.println("</body>");
out.println("</html>");
out.close();
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>This is the MySQL Servlet</h2>
<form action = "/database/database" method = "get">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<input type = "text" name = "query" />
<input type = "submit" value = "Run MySQL Servlet" />
</label>
</p>
</form>
</body>
</html>
I thought another potential failure point could be my path to the database file, which is initialized in my web.xml file. An example I found online included the port, but I'm wondering if I should remove the port number. Does anyone know the default port to use for MySQL?
This is the specific line I'm talking about from the xml file below:
jdbc:mysql://localhost:3309/project4
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<!-- General description of the web application -->
<display-name>
MySQL Servlet
</display-name>
<description>
This web application allows the user to connect to a database, sumbit queries, and make changes.
</description>
<!-- Servlet definitions -->
<servlet>
<servlet-name>database</servlet-name>
<description>
A servlet that handles SQL commands submitted by the user.
</description>
<servlet-class>
databaseServlet
</servlet-class>
<init-param>
<param-name>databaseDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>databaseName</param-name>
<param-value>jdbc:mysql://localhost:3309/project4</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>pass</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>database</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>
</web-app>
I was using port 3309, and needed to use port 3306.
PROBLEM
jdbc:mysql://localhost:3309/project4
SOLUTION
jdbc:mysql://localhost:3306/project4

Categories

Resources