This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have written a Java servlet program and run it through local Tomcat 7, But it was showing following error :
HTTP Status 404 - /skypark/registration
type Status report
message /skypark/registration
description The requested resource is not available.
Apache Tomcat/7.0.33
I don't know what was the reason for it
my Html page is
<html>
<head>
<title>
User registration
</title>
</head>
<body>
<form action="registration" method="post">
<center>
<h2><b>Skypark User Registration</b></h2>
<table border="0">
<tr><td>
First Name
</td><td>
<input type="text" name="fname"/></br>
</td></tr><tr><td>
Last Name
</td><td>
<input type="text" name="lname"/></br>
</td></tr><tr><td>
UserName
</td><td>
<input type="text" name="uname"></br>
</td></tr><tr><td>
Enter Password
</td><td>
<input type="password" name="pass"></br>
</td></tr><tr><td>
Re-Type Password
</td><td>
<input type="password" name="pass1"></br>
</td></tr><tr><td>
Enter Email ID
</td><td>
<input type="email" name="email1"></br>
</td></tr><tr><td>
Phone Number
</td><td>
<input type="number" name="phone">
</td></tr><tr><td>
Gender<br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Male">Male</input></br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Female">Female</input></br>
</td></tr><tr><td>
Enter Your Date of Birth<br>
</td><td>
<Table Border=0>
<tr>
<td>
Date
</td>
<td>Month</td>
<td>Year</td>
</tr><tr>
<td> <select name="date">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
.
.
.
have some code
.
.
.
</table>
<input type="submit" value="Submit"></br>
</center>
</form>
</body>
</html>
My servlet is :
package skypark;
import skypark.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Registration extends HttpServlet
{
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:#JamesPJ-PC:1521:skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
try
{
String phone1,uname,fname,lname,dob,address,city,state,country,pin,email,password,gender,lang,qual,relegion,privacy,hobbies,fav;
uname=req.getParameter("uname");
fname=req.getParameter("fname");
lname=req.getParameter("lname");
dob=req.getParameter("date");
address=req.getParameter("address");
city=req.getParameter("city");
state=req.getParameter("state");
country=req.getParameter("country");
pin=req.getParameter("pin");
email=req.getParameter("email1");
password=req.getParameter("password");
gender=req.getParameter("gender");
phone1=req.getParameter("phone");
lang="";
qual="";
relegion="";
privacy="";
hobbies="";
fav="";
int phone=Integer.parseInt(phone1);
Connection con=prepareConnection();
String Query="Insert into regdetails values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(Query);
ps.setString(1,uname);
ps.setString(2,fname);
ps.setString(3,lname);
ps.setString(4,dob);
ps.setString(5,address);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,country);
ps.setString(9,pin);
ps.setString(10,lang);
ps.setString(11,qual);
ps.setString(12,relegion);
ps.setString(13,privacy);
ps.setString(14,hobbies);
ps.setString(15,fav);
ps.setString(16,gender);
int c=ps.executeUpdate();
String query="insert into passmanager values(?,?,?,?)";
PreparedStatement ps1=con.prepareStatement(query);
ps1.setString(1,uname);
ps1.setString(2,password);
ps1.setString(3,email);
ps1.setInt(4,phone);
int i=ps1.executeUpdate();
if(c==1||c==Statement.SUCCESS_NO_INFO && i==1||i==Statement.SUCCESS_NO_INFO)
{
out.println("<html><head><title>Login</title></head><body>");
out.println("<center><h2>Skypark.com</h2>");
out.println("<table border=0><tr>");
out.println("<td>UserName/E-Mail</td>");
out.println("<form action=login method=post");
out.println("<td><input type=text name=uname></td>");
out.println("</tr><tr><td>Password</td>");
out.println("<td><input type=password name=pass></td></tr></table>");
out.println("<input type=submit value=Login>");
out.println("</form></body></html>");
}
else
{
out.println("<html><head><title>Error!</title></head><body>");
out.println("<center><b>Given details are incorrect</b>");
out.println(" Please try again</center></body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
}
catch(Exception e)
{
out.println("<html><head><title>Error!</title><body>");
out.println("<b><i>Unable to process try after some time</i></b>");
out.println("</body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
out.flush();
out.close();
}
}
And the web.xml file is
<?xml version="1.0" encoding="UTF-8"?>
<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"
metadata-complete="true">
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>skypark.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
</web-app>
This i kept in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\web.xml
and servlet class in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\classes\skypark
and registration.html in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\
if any mistake in this makes above error means please help me.Thanks in advance....
I think the problem is with this two line :
<form action="registration" method="post"> in your html page.
<url-pattern>/Registration</url-pattern> in your web.xml
Your action is set to registration and your url pattern expects Registration (Note that capital R and small r ).
Just try changing them (both same ) and it should work
Try putting a request mapping to the method you want to be called by the request. If, for example, you use Spring framework, you need to set your servlet url-pattern in web.xml to htm in your case, then return the name of your html file.
#RequestMapping(value ="/registration",method = RequestMethod.GET)
public String render(Model model, HttpServletRequest request, HttpServletResponse response) {
{
--------------- compute ----
return "registration";
}
If you will put a request to /registration, the server will compute the method mapped to it then search for "registration" (returned value) to show.
Hope it helps !
Related
I keep getting the error This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 405
I created a signup form. but when I submit, it doesn't show the action page.
**In html:
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Signup Form</title>
<link rel="stylesheet" href="\assets\css\main.css">
</head>
<body>
<nav class="flex-container">
<div class="one"><img src="\assets\images\vanierlogo.jpg" alt="logo"></div>
<div class="two"><a href=\signup.html>Signup</a></div>
<div class="three">Login</div>
</nav>
<div id="txtHint"></div>
<form>
<h3>Create New Student Account</h3><br><br>
<label for="username">Student ID: </label>
<input type="text" id="username" name="username" required><br><br>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="firstName"><br><br>
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="lastName"><br><br>
<label>Enter Password<sup>*</sup>: </label>
<input type="password" autocomplete="passwd" name="passwd" required><br><br>
<label>Confirm Password: </label>
<input type="password" autocomplete="passwd1" name="passwd1" required><br><br>
<label>Are you Full-Time or Part-Time?</label><br><br>
<label for="Full-Time">Full-Time</label>
<input type="radio" id="Full-Time" name="status" value="Full-Time">
<label for="Part-Time">Part-Time</label>
<input type="radio" id="Part-Time" name="status" value="Part-Time"><br><br>
<input type="submit" onclick="createAccount(this)" value="Sign Up!"><br><br>
<footer>* Password must be at least 3 characters in length</footer>
</form>
<script src="\assets\js\main.js"></script>
</body>
</html>
In main.js:
function createAccount(element) {
const currForm = element.closest('form');
const params = "username="+currForm.elements[0].value +
"&firstName="+currForm.elements[1].value +
"&lastName="+currForm.elements[2].value +
"&passwd="+currForm.elements[3].value +
"&passwd1="+currForm.elements[4].value +
"&status="+currForm.elements[5].value;
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:80/SignupHandlingServlet",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhttp.readyState == 4) {
alert("DONE");
alert(xhttp.status);
if (xhttp.status==409 || xhttp.status==417 || xhttp.status==200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
else {
alert(xhttp.method);
let response = JSON.parse(xhttp.responseText);
document.querySelector("#ipText").innerHTML = response.ip;
}
}
else if (xhttp.readyState==0) {
alert("request unsent");
} else if (xhttp.readyState==1){
alert("request OPENED");
} else if(xhttp.readyState==2) {
alert("request HEADERS_RECEIVED");
} else {
alert("The HTTP request response is being downloaded");
}
}
}
**In web.xml:
**
<web-app>
<servlet>
<servlet-name>SignupHandlingServlet</servlet-name>
<servlet-class>SignupHandlingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupHandlingServlet</servlet-name>
<url-pattern>/SignupHandlingServlet</url-pattern>
</servlet-mapping>
</web-app>
**In java:
**
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
#WebServlet("/SignupHandlingServlet")
public class SignupHandlingServlet extends HttpServlet {
/* Process the HTTP Post request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Obtain parameters from the client
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
if (Interpreter.usernameExists(username)) {
out.println("<br><br>That username already exists.<br>");
response.setStatus(417);
}
else if (!passwd.equals(request.getParameter("passwd1"))) {
out.println("<br><br>Please confirm password<br>");
response.setStatus(409);
}
else {
String lastName = request.getParameter("lastName");
String firstName = request.getParameter("firstName");
String status = request.getParameter("status");
Student CreateStudent = new Student(username, passwd, firstName, lastName, status);
Interpreter.saveStudentCredentials(CreateStudent);
out.println("<br><br>Account created successfully<br>");
response.setStatus(200);
}
out.close(); // Close stream
}
}
Any help please? it's my 1st front end school project. It's been long debugging this error with no success.
I was expecting a createAccount page with result of the doPost() printed out.
click here to view my folder structure
When submitting a form, only input fields with the name attribute are submitted.
For inputs 'username', 'new-password' and 'new-password1', there is no name attribute and hence no data sent to server. So, accessing 'passwd' variable (which is null) with equals method will throw 'NullPointerException'.
My code is to use java servlets and JDBC to store and retrieve the information from a database. There is no error in the IDE the program is running but, the rows aren't inserted into the database and an error occurred in the firefox browser.
The following code is from the SERVLET file
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ServletRegister extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter("text/html");
String uname = req.getParameter("uname");
String passwd = req.getParameter("passwd");
String email = req.getParameter("email");
int phno = Integer.parseInt(req.getParameter("phno"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hack","root","");
PreparedStatement ps = con.prepareStatement("insert into student values(?,?,?,?)");
ps.setString(1,uname);
ps.setString(2,passwd);
ps.setString(3, email);
ps.setInt(4, phno);
int i = ps.executeUpdate();
if(i>0)
out.print("Registerd Successfully");
out.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The following code is from HTML file
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="register">
<table>
<tr>
<td>Enter User Name: <input type="text" name="uname"> </td>
</tr>
<tr>
<td>Enter Password: <input type="password" name="passwd"> </td>
</tr>
<tr>
<td>Enter E-mail: <input type="email" name="email"> </td>
</tr>
<tr>
<td>Enter Phone.no: <input type="number" name="phno" min="6000000000" max="9999999999"></td>
</tr>
<tr>
<td><input type="submit"> <input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is from web.xml file
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hacker.ServletRegister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
The Error is:
Error obtained in firefox browser
You can use Postman to send a POST request to your server, or change doPost to doGet
In HTML file tag you did not mention the method= "post" So its taking the value by default "get" request.
I am trying to create a page that will code that will take in student information from html and use java servlets to catch the information and put into Google Cloud Datastore.
I have the HTML working but whenever I try to run it the page just refreshes and doesn't put anything into the cloud datastore.
I am new to servlets so I'm not sure what I am missing.
Below is the jsp file (i.e add_student.jsp)
<%# 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>Insert title here</title>
</head>
<body>
Add Student
Search Student
Update Student
Delete Student
<form method="post">
<p>Student Number <input name="student_number" type="number" required /></p>
<p>First Name <input name="f_name" type="text" required/></p>
<p>Last Name <input name="l_name" type="text" required/></p>
<p>Address (temporary) <input name="temp_address" type="text" required/></p>
<p>Address (permanent) <input name="perm_address" type="text" required/></p>
<p>Home Number <input name="home_number" type="number" required/></p>
<p>Mobile Number <input name="mobile_number" type="number" required/></p>
<p>Date of Birth <input name="birth_date" type="date" required/></p>
<p>Gender <p>Gender: <br>
<input type="radio" name="gender" value="M" required checked> Male<br>
<input type="radio" name="gender" value="F" required> Female<br>
<p>Major <input name="major" type="text" required/></p>
<p>Course <input name="course" type="text" required/></p>
<p>Study Mode <p>Study Mode: <br>
<input type="radio" name="study_mode" value="full_time" checked> Full-Time<br>
<input type="radio" name="study_mode" value="part_time" required> Part-Time<br>
<p>Start Date <input name="start_date" type="date" required /></p>
<p>End Date <input name="end_date" type="date" required /></p>
<p>Add Student <input name="submitButton" type="submit" value="addStudent" /></p>
</form>
</body>
</html>
Here's the java Servlet file (i.e add_studentServlet.java)
package assignment_redo;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.*;//import the datastore files from google
#SuppressWarnings("serial")
public class add_studentServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
String title ="Using the GET Method to Read Form Data!";
String student_number = req.getParameter("student_number");
String f_name =req.getParameter("f_name");
String l_name=req.getParameter("l_name");
String perm_address = req.getParameter("perm_address");
String temp_address = req.getParameter("temp_address");
String home_number = req.getParameter("home_number");
String mobile_number = req.getParameter("mobile_number");
String birth_date = req.getParameter("birth_date");
String gender = req.getParameter("gender");
String major = req.getParameter("major");
String course = req.getParameter("course");
String study_mode = req.getParameter("study_mode");
String start_date = req.getParameter("start_date");
String end_date = req.getParameter("end_date");
// //creating an object of type DatastoreService
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//creating a new entity of type employee
Entity student = new Entity("Student", student_number);
//set its properties
student.setProperty("f_name", f_name);
student.setProperty("l_name", l_name);
student.setProperty("student_number", student_number);
student.setProperty("temp_address", temp_address);
student.setProperty("perm_address", perm_address);
student.setProperty("home_number", home_number);
student.setProperty("mobile_number", mobile_number);
student.setProperty("birth_date", birth_date);
student.setProperty("gender", gender);
student.setProperty("major", major);
student.setProperty("course", course);
student.setProperty("study_mode", study_mode);
student.setProperty("start_date", start_date);
student.setProperty("end_date", end_date);
//insert student entity into Datastore
datastore.put(student);
//display success message now
resp.getWriter().println("Student with id "+student_number+" added to the system!");
}
}
You have to indicate in your jsp that you are submitting the form to your servlet:
<form action="addStudent" method="post">
This makes the assumption that in the web.xml you have configured your servlet as follow:
<servlet>
<servlet-name>add_studentServlet</servlet-name>
<servlet-class>assignment_redo.add_studentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add_studentServlet</servlet-name>
<url-pattern>/addStudent</url-pattern>
</servlet-mapping>
Then you have to put your code in the doPost of your servlet, not in the doGet.
This question already has answers here:
How to call servlet class from HTML form
(2 answers)
Closed 7 years ago.
How to call servlet file from html.I tried but when i click on submit its not taking any action,I am not getting any error also. and i want to submit data in database.action event is not working.Please help me
HTML code
<form name="form" method="post" action="NewServlet" >
<label for='name' ><font size="2">Your Full Name*: </label><br/>
<input type='text' name='name' id='name' maxlength="50" style="height:30px; width :250;" placeholder="Enter Full Name"/><br/><br/>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' maxlength="50" style="height:30px; width :250;" placeholder="Enter your Email"/><br/><br/>
<label for='phone' >Phone Number*:</label><br/>
<input type='text' name='phone' id='phone' maxlength="15" style="height:30px; width :250;" placeholder="Enter Phone Number"/><br/><br/>
<label for='Reason' >Reason*:</label><br/>
<select name="reason" style="height:30px; width :250;">
<option>Select</option>
<option>Enquiry</option>
<option>Complain</option>
<option>Order</option>
</select>
</br>
</br>
</br>
<label for='message' >Address Or Message:</label><br/>
<textarea style="height:100px; width :400;" name='message' id='message' placeholder="Enter Address or Message"></textarea></p>
</b>
</size>
<%--
<input type='submit' name='btnSubmit' value="Submit"/>
--%>
<img src="Image/submit1.png" style="width:150px; height:70px;top:50%px; " onmouseover="this.src='Image/submit2.png'" onmouseout="this.src='Image/submit1.png'"/>
</form>
Servlet code
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String driver= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://localhost:1433;databaseName=wristwatch; username=sa; password=abc#123;";
try {
//int id=Integer.parseInt(request.getParameter("txt_id"));
String nm=request.getParameter("name");
String email=request.getParameter("email");
int phone=Integer.parseInt(request.getParameter("phone"));
String reason=request.getParameter("reason");
String add=request.getParameter("Address");
Class.forName(driver);
Connection c=DriverManager.getConnection(url);
out.println("Data Inserted");
}
catch(Exception e)
{
System.out.print(e);
}
finally {
out.close();
}
}
web.xml
<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>
Change the processRequest(...){...} to doPost(...){...} in servlet.
This link might make you clear.
ProcessRequest Method
I am learning JSP through a French JSP book full of tutorials. I'm currently learning "MVC & Jsp" basically, with a Catalog of DVD and a Shopping cart. A controller adds dvds to the cart when the user clicks on the add button.
However, it appears that my controller isn't called. I place a System.Out when it is called to check if it works, and there is no text popping on my console...
Here is my project explorer.
And here are my codes for my catalog and my Controller.
<%#page import="exoLivres.ShoppingCart"%>
<%# page errorPage="../PagesErreur/Erreurpage.jsp" %>
<jsp:useBean id="cart" scope="session" class="exoLivres.ShoppingCart" />
<html>
<head>
<title>Catalogue DVD</title>
</head>
<body>
Quantité actuelle : <%=cart.getNumOfItems() %>
<hr>
<center><h3>Catalogue DVD</h3></center>
<table border="1">
<tr><th>Description</th><th>Prix</th></tr>
<tr>
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>Frozen</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Frozen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
<tr>
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>XMen Origins</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="XMen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
<tr>
<form action="ShopController" method="post">
<td>Avengers</td>
<td>$17.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Avengers">
<input type="hidden" name="price" value="17.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
</table>
</body>
</html>
and my controller
package exoLivres;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import exoLivres.ShoppingCart;
public class ShopController extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println("Contrôleur démarré");
String command= request.getParameter("command");
HttpSession session = request.getSession();
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
if(command.equals("add")){
String id = request.getParameter("id");
if (id!=null){
System.out.println(id);
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
System.out.println(id + desc + price);
}
}
response.sendRedirect("U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp");
}
public String getServletInfo(){
return "ShopController Information";
}
}
I guess the problem is from my references to my Controller but I can't think of the correct reference. Any help welcome =)
EDIT
Okay so here is my web.xmm [I also did the modifications suggered on my code above, and removed every "e" I wrote at the end of method (and not methode)]
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>MyfirstServlet</servlet-name>
<servlet-class>myfirstProject.MyfirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyfirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Books</servlet-name>
<servlet-class>myfirstProject.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Books</servlet-name>
<url-pattern>/books</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShopController</servlet-name>
<servlet-class>exoLivres.ShopController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShopController</servlet-name>
<url-pattern>/ShopController</url-pattern>
</servlet-mapping>
</web-app>
I think the problem is the way you set action to the form.
action="U:/workspace/myfirstProjet/src/ShopController"
I think it should be action="Name_Of_CLass" not path to the class.
Also notice that the sendRedirect receives a url location not the path to the jsp in your project. (https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html#sendRedirect%28java.lang.String%29)
So in your servlet (controller) and your jsp, rename this "U:/workspace/myfirstProjet/build/classes/exoLivres/ShopController" to something like this: "/myfirstProjet/".
and where you have "U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp"
rename to "/myfirstProjet/".
You must have your controller mapping in the web.xml
You have not given path of your ShopController controller in this
<servlet>
<servlet-name>MyfirstServlet</servlet-name>
<servlet-class>myfirstProject.MyfirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyfirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Books</servlet-name>
<servlet-class>myfirstProject.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Books</servlet-name>
<url-pattern>/books</url-pattern>
</servlet-mapping>
It should be like this
<servlet>
<servlet-name>ShopController</servlet-name>
<servlet-class>packagename.ShopController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShopController</servlet-name>
<url-pattern>/ShopController</url-pattern>
</servlet-mapping>
And change the action of your jsp form as below..
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>XMen Origins</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="XMen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
To prevent get method not supported change controller like this
public class ShopController extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response)
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response)
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println("Contrôleur démarré");
String command= request.getParameter("command");
HttpSession session = request.getSession();
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
if(command.equals("add")){
String id = request.getParameter("id");
if (id!=null){
System.out.println(id);
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
System.out.println(id + desc + price);
}
}
response.sendRedirect("U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp");
}
}