Resource not found due to misconfiguration - java

I am developing a Web application based on Tomcat 7, and bumped in a situation where I have no clue what and why is happening. After typing my login credentials in JSP page below:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Login</title>
</head>
<body>
<div id="form">
<form method=POST name=login_form action=Login>
Usuário: <input type=text name=username> <br/>
Senha: <input type=password name=password> <br/>
<input type="submit" value="Entrar">
<span class="error">${error}</span>
</form>
</div>
</body>
</html>
I receive the following message, regardless if I entered the right or wrong credentials:
HTTP Status 404 - /WebApp/Login
type Status report
message /WebApp/Login
description The requested resource is not available.
Apache Tomcat/7.0.42
The implementation for the method doPost of the servlet class is the following:
String username = request.getParameter("username");
String password = request.getParameter("password");
Date data_login = new Date(System.currentTimeMillis());
java.sql.Timestamp nova_data = new java.sql.Timestamp(0, 0, 0, 0, 0, 0, 0);
nova_data.setDate(data_login.getDay());
nova_data.setMonth(data_login.getMonth());
nova_data.setYear(data_login.getYear());
nova_data.setHours(data_login.getHours());
nova_data.setMinutes(data_login.getMinutes());
nova_data.setSeconds(nova_data.getSeconds());
DataHelper dhelper = new DataHelper();
try {
System.out.println("Registrando login...");
user temp = dhelper.doProcessaLogin(username, password);
if (temp != null) {
String fname = temp.getFirstName();
String lname = temp.getLastName();
int id = temp.getId();
System.out.println("Dados corretos");
request.getSession().setAttribute("user", fname+" "+lname);
dhelper.doRegistraSessao(fname, lname, nova_data, id);
Cookie ck = new Cookie("User",fname+" "+lname);
ck.setMaxAge(7);
response.addCookie(ck);
request.getRequestDispatcher("/WEB-INF/menu.jsp")
.forward(request,response);
}
else {
System.out.println("Dados incorretos");
request.getSession().setAttribute("erro",
"Não foi possivel efetuar o login");
System.out.println("Direcionando de volta para a pagina de login");
request.getRequestDispatcher("/login").forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have an implementation for a method doGet too:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
my web.xml is the following:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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" version="3.0">
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.webapp.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
I really don't know the reason the system is looking for /WebApp/Login instead of /WebApp/login, which is what was declared in the web.xml. Someone can see any problem with the code above?

Try replacing action=Login by action=login (lowercase L) in your JSP page. Tomcat is case sensitive and you declared the URL pattern for the servlet mapping as "/login". If it still doesn't work, try with action=/login.

The problem is in your form page. See where it says action=Login (you should use quotes, by the way, both for readability and for safety)? That's telling the Web browser that the URL it should submit to is Login relative to the page it's already on, which is probably /WebApp/index.jsp. Fix that form tag.

Related

404 when servlet is invoked but works directly when url to servlet is used from browser

Problem: When I invoke url (url-mapping) directly in the browser it works pretty well but when I use post method to invoke servlet from jsp file, it does not work but gives an error:
Type Status Report
Message /HelloWorld/myservlet
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
Jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="myservlet">
<input type="submit" value ="send">
</form>
</body>
</html>
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/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>helloworld2</display-name>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>apress.helloworld.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Servlet code:
package apress.helloworld;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
//System.out.println("Get Method Called");
try { response.setContentType("text/html");
`enter code here` PrintWriter printwriter = response.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
try { resp.setContentType("text/html");
PrintWriter printwriter = resp.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="hello">
<input type="submit" value ="send">
</form>
</body>
</html>
use Above code
in HTML form action="url-mapping" you have to mention url pattern of servlet not servlet name refer your web.xml

Java Web Application Edit is Not Working

I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception
Here is my HTML code display all the records .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Posts</title>
</head>
<body>
<div style="width: 1200px; margin-left: auto; margin-right: auto;">
<table cellpadding="10">
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Detail</th>
<th>Category</th>
<th>Date</th>
<th>Image</th>
<th></th>
</tr>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.title}...</td>
<td>${p.description}...</td>
<td>${p.detail}...</td>
<td>${p.category}</td>
<td>${p.date}...</td>
<td>${p.image}...</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is the HTML for EidtPost.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit</title>
</head>
<body>
<h1>Edit News</h1>
<div style="width: 900px; margin-left: auto; margin-right: auto">
<c:forEach items="${getNewsById}" var="p">
<form action="JSP/ManagerEditPost.jsp" method="post">
<input type="hidden" name="id" value="${p.id}">
Title:<br>
<input type="text" value="${p.title}" name="title" style="width: 200px"><br>
Description:<br>
<input type="text" value="${p.description}" name="description" style="width: 200px"><br>
Detail:<br>
<textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
Category:
<select name="category">
<option value="${p.category}">${p.category}</option>
<option value="World">World</option>
<option value="Tech">Tech</option>
<option value="Sport">Sport</option>
</select><br>
Image:<br>
<input type="text" value="${p.image}" name="image" style="width: 200px"><br>
<input type="submit" value="Submit">
</form>
</c:forEach>
</div>
</body>
</html>
Here is the Data Access code for CRUD operation.
public void edit(int id, String title, String description, String detail, String category, String image){
try {
String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
PreparedStatement ps= DBUtils.getPreparedStatement(sql);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, detail);
ps.setString(4, category);
ps.setString(5, image);
ps.setInt(6, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is the servlet code .
#WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
{
String idTemp = request.getParameter("id");
int id = Integer.parseInt(idTemp);
request.setAttribute("getNewsById", DataAccess.getNewById(id));
RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
try {
rd.forward(request, response);
} catch (ServletException | IOException ex) {
Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code 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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>EditPost</servlet-name>
<servlet-class>servlet.EditPost</servlet-class>
</servlet>
<servlet>
<servlet-name>DeletePost</servlet-name>
<servlet-class>servlet.DeletePost</servlet-class>
</servlet>
<servlet>
<servlet-name>AllPost</servlet-name>
<servlet-class>servlet.AllPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditPost</servlet-name>
<url-pattern>/EditPost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeletePost</servlet-name>
<url-pattern>/DeletePost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AllPost</servlet-name>
<url-pattern>/AllPost</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Here is the screen shot of the error when i click the edit and delete link .
The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.
Ultimately, the path in the .jsp needs to match to the #WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.
This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.
web.xml
This provides the basic information.
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
welcome.jsp
This is just an example .jsp that provides an href.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- note this can also be ./EditPost -->
<!-- also note that not passing any query here -->
Edit Post
</body>
</html>
EditPost.java
This is a quick example of an annotated servlet.
#WebServlet("/EditPost")
public class EditPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public EditPost() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

Jersey- Rest: 404 not found error

I am doing a simple program , the task is to Get (user id) from html form over Rest and username associated with should be displayed. I am
getting a 404 error when I load the index.html page.
But when i give the values(userid) over the url it works fine.
here's the code
<!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>Index page</title>
</head>
<body>
<form action="http://localhost:8080/rest/my/first/rest/users" method="GET">
<label for="uid">ID</label>
<input name="uid" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and here is the resource class
#Path("users") //attach client request to resource: .../users
public class RestResource {
Map<String,User> listUsers;
//initialize some resources
public RestResource(){
listUsers = new HashMap();
listUsers.put("1",new User("1", "John"));
listUsers.put("2",new User("2", "Peter"));
}
//return list of users
#GET
#Produces(MediaType.TEXT_PLAIN)
public String listOfUsersInText(){
String list="";
for (Entry<String,User> u:listUsers.entrySet()){
list += u.getValue().getName() + "\n";
}
return list;
}
//return user information corresponding to the requested uid.
#GET
#Path("{uid}") //attach client request to resource: .../users/<uid>
#Produces(MediaType.TEXT_PLAIN)
public String getUID(#PathParam("uid") String uid){
if (!listUsers.containsKey(uid))
return "User not exist!";
return listUsers.get(uid).getID()+":"+listUsers.get(uid).getName();
}
}
WEB.xml
<display-name>rest</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>my.first.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
The approach you have followed is wrong we have several rest client api's you can use any of those and can send the request to rest resource
The response data you can display in jsp pages.

How to call servlet when button click [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
As new to the jsp and servlet and only having basic idea of it and still learning .I want to know how can we call the servlet class on that button click.I m using button in place of submit button
Here is the page content:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>JSON DATA EXAMPLE</title>
<script type="text/javascript">
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.location.href="JsonServlet";
return false;
}
}
</script>
</head>
<body>
<div>
<form name="getdata" action="JsonServlet" method="post">
<input type="button" name="fetchdata" value="CLick to get data" onclick="return callservlet();">
</form>
</div>
</body>
</html>
and here the servlet class content
public class JsonServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
JsonParser parser=new JsonParser();
if(req.getParameter("fetchdata")!=null)
{
System.out.println("Button Clicked");
}
else
{
System.out.println("Button not clicked");
}
}
}
and here is the web.xml part
<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_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JsonDataExample</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jsonfetch</servlet-name>
<servlet-class>com.text.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jsonfetch</servlet-name>
<url-pattern>/JsonServlet</url-pattern>
</servlet-mapping>
</web-app>
so is there any part i m write the method wrong because its gives me 404 error resource not found
so i want the concept that on that button click how can i call my servlet class.Thanks for any reply
try this :
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.forms[0].action = "JsonServlet"
document.forms[0].submit();
}
}
You can't set the location to a servlet. Instead, what you should do to hit the servlet is to submit your form:
function callservlet() {
//do your processing.
document.getElementsByName('getdata')[0].submit();
}
Or you can simply use a submit type button.
You just need to submit your form - (Instead of document.location.href="JsonServlet";)
document.getElementByName('getdata').submit();
I want to know how can we call the servlet class on that button
click.I m using button in place of submit button
You don't need js here, you can do it with the existing form itself. Replace the input tag as follows:
<input type="submit" name="fetchdata" value="CLick to get data" />
If you still want to use js, try below script instead:
function callservlet() {
document.forms.getdata.submit();
}

Import servlet in JSP Index => Null parameter

I'm currently working on a school project. We have to do a small market website in Java.
I've a small problem. I have an Index.jsp where i want to include a servlet (RandomArticle.jsp). This servlet have a .jsp and a .java and just shuffle a collection and return names.
When I display index.jsp, the html of RandomArticle.jsp is well displayed (so the include is correct) but the returned name are "null".
Here is some code:
Index.jsp (in WebContent of eclipse)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Market</title>
</head>
<body>
<header>
<h1>market 2013</h1>
<h2>Bievenue </h2>
</header>
<nav>
<% String include = "/WEB-INF/RandomArticle.jsp"; %>
<jsp:include page='<%=include%>' />
</nav>
</body>
</html>
RandomArticle.jsp (in WEB-INF):
<h1>Liste des produits EpiMarket</h1>
<%
String productName1 = (String) request.getAttribute("productName1");
String productName2 = (String) request.getAttribute("productName2");
String productName3 = (String) request.getAttribute("productName3");
%>
<p>Acheter <% out.println(productName1); %></p>
<p>Acheter <% out.println(productName2); %></p>
<p>Acheter <% out.println(productName3); %></p>
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Market</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>fr.market.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RandomArticle</servlet-name>
<servlet-class>fr.market.servlets.RandomArticle</servlet-class>
</servlet>
</web-app>
and RandomARticle.java
public class RandomArticle extends HttpServlet {
private ArrayList<Object> allProducts;
public String getProductName(int index){
return (((AbstractProduct) allProducts.get(index)).getName());
}
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
ADAO<AbstractProduct> dao = new DAOProduit();
allProducts = ((DAOProduit) dao).getAll();
Collections.shuffle(allProducts);
request.setAttribute("productName1", getProductName(0));
request.setAttribute("productName2", getProductName(1));
request.setAttribute("productName3", getProductName(2));
this.getServletContext().getRequestDispatcher( "/WEB-INF/RandomArticle.jsp" ).forward( request, response );
}
}
I think that the .java is never called, but I don't understand why.
Thanks for your time.
Gilles

Categories

Resources