Simple J2ee program is not working - java

this is structure of projectThis servlet is placed in servlets package
package Servlets;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class OpenAccountServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
String fatherName=request.getParameter("fathername");
String webPage=null;
webPage+="<html>";
webPage+="<head>";
webPage+="</head>";
webPage+="<body>";
webPage+=firstName;
webPage+=lastName;
webPage+=fatherName;
webPage+="</body>";
webPage+="</html>";
out.println(webPage);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
doGet(request,response);
}
public void destroy(){
}
}
this is jsp page which i am using for accepting data from user.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="openaccount.do">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value=""></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value=""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit">
<input type="button" name="cancel" value="Cancel">
</td>
</tr>
</table>
</form>
</body>
</html>
and this is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<servlet>
<servlet-name>Open_Account_controller</servlet-name>
<servlet-class>Servlets.OpenAccountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Open_Account_controller</servlet-name>
<url-pattern>/openaccount.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
and whenever i am trying to run this, 404 error. i am using intelliJ idea IDE for development, and i am using 64 bit tomcat.

Try <form method="post" action="../openaccount.do">
When you remove the leading ../ It would try to load the url relative to current directory.
Better yet use a more generic form like:
action="${pageContext.request.contextPath}/openaccount.do"

Related

HTTP Status 405 - Method Not Allowed - while using servlet

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.

jsp servlet can't show up using intelling ide and tomcat 505 internal error server

I can't open my jsp file even though I had configured the ward exploded and tomcat server using servlet controllers .
I tried to look on different error in stackoverflow and other websites but couldn't really find the appropriate error solver.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class ControleurServlet extends HttpServlet {
private IAccountDAO account;
#Override
public void init() {
account = new AccountDAOImpl();
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletPath();
if (path.equals("/index.php")) {
req.getRequestDispatcher("Accounts.jsp").forward(req, resp);
}
else if (path.equals("/search.php")){
String keyWord=req.getParameter("keyWord");
AccountModel model=new AccountModel();
model.setKeyword(keyWord);
List<Account> accounts= account.accountsValues("%"+keyWord+"%");
model.setAccounts(accounts);
req.setAttribute("model",model);
req.getRequestDispatcher("Accounts.jsp").forward(req,resp);
}
}
}
and here's my jsp file
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Accounts</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<%#include file="header.jsp" %>>
<div class="container col-md-10 col-md-offset-1">
<div class="panel panel-primary">
<div class="panel-heading">Search Users:</div>
<div class="panel-body">
<form action="search.php" method="get">
<label>Keyword</label>
<input type="text" name="keyWord">
<button type="submit" class="btn btn-primary">Search</button>
</form>
<table class="table">
<tr>
<th>User_Id</th><th>Creation_Date</th><th>Username</th><th>Password</th>
</tr>
<c:forEach items="${model.account}" var="acc">
<tr>
<td>${acc.user_id}</td>
<td>${acc.creation_date}</td>
<td>${acc.username}</td>
<td>${acc.password}</td>
<td><a onclick="return confirm("Are you sure?")" href="delete.php?id=${acc.user_id}">delete</a> </td>
<td>Edit </td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
</body>
</html>
It keeps showing me the 505 error while trying to open my http://localhost:3030/Banque_war_exploded/index.php,
and here's my web.xml file too
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
version="4.0">
<display-name>Banque</display-name>
<servlet>
<servlet-name>cs</servlet-name>
<servlet-class>couche.presentation.ControleurServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cs</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
</web-app>
and the error trace code
org.apache.jasper.JasperException: /Accounts.jsp (ligne: [30], colonne: [16]) D'après la TLD, l'attribut [items] n'accepte aucune expression
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:292)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:115)
org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1250)
org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:888)
org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1544)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2389)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2441)
org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2447)
org.apache.jasper.compiler.Node$Root.accept(Node.java:470)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2389)
org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1857)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:224)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:386)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:362)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:346)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:605)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:400)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
couche.presentation.ControleurServlet.doGet(ControleurServlet.java:26)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Sign In page using SQL SERVER, JAVA, Servlets, Eclipse

Here is my code, it is connecting to database, in the console I could see the msg "connected" but the problem is after giving the user credentials it is not navigating to the next page(welcome.jsp) and it just shows a msg that "username or password error" could someone help me out
LoginServlet.java
package com.amzi.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://WMDENTW1\\SQLEXPRESS:1433;" +
"database=FullTextDB;" +
"user=root;" +
"password=root123";
Connection conn = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
PreparedStatement pst = conn.prepareStatement("select User, Password from dbo.AdminLogin where User=? and Password=?");
pst.setString(1, n);
pst.setString(2, p);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("page opened");
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
} else {
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
}
index.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="LoginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4> Hello, <%=session.getAttribute("name")%></h4>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <servlet> <servlet-name>login</servlet-name> <servlet-class>com.amzi.servlets.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app>
In response your your request to clarify my comment, instead I shall write it as an answer.
IN your doPost method, you have this line:
PrintWriter out = response.getWriter();
After that, you use out to write directly to the response, such as in these lines:
out.println("page opened");
and
out.print("<p style=\"color:red\">Sorry username or password error</p>");
However, you then go and forward to a JSP:
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
But that does the same thing - after processing the JSP it sends the result to the response PrintWriter, just have you have done.
You really shouldn't do both. Just use the JSPs.
Secondly, your message 'username or password error' indicates that the query returned no rows, so the username/password you used is probably wrong. I can't see anything wrong with the JDBC code or query.

Unsuccessful redirecting of servlet based using string query parameters

Situation: In the code below I'm attempting to learn how to use form parameters specifically redirecting Java servlets by propagating string query parameters.
Problem: I can't seem to figure out why I'm facing a problem with re-directing the user from the form i.e. index.html using the desired string query paramters to the correct page.
Below are the steps I took before posting this up:
I made sure the URL pattern for the #WebServlet annotation is correct
i.e. in my case /CityManagerWebStarter/mainmenuresponder.do
I made sure my content-root when looking at the URL is correct i.e.
/CityManagerWebStarter and I can confirm this as when I launch the
following URL http://localhost:8080/CityManagerWebStarter/ it
displays the index.html page as expected.
Below is my servlet code and following that is my index.html code and ListCities.html is an example of a page I'm attempting to re-direct the user to:
servlet code:
package company.citymanagerweb.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MainMenuResponder
*/
#WebServlet("/CityManagerWebStarter/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MainMenuResponder() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userChoiceSelect = request.getParameter("menuChoice");
String[] userOptionsCBox = request.getParameterValues("adminoptions");
StringBuilder params = new StringBuilder();
String queryStringParams = params.toString();
if(userOptionsCBox != null) {
boolean isFirst = true;
for(int i = 0; i < userOptionsCBox.length; i++) {
// Build URL with string query parameters i.e. URL + ? + PARAM1 + AMAPERSAND + PARAM2
// Arguments is value of the value attribute
if(!isFirst) {
params.append("&");
} else {
params.append("?");
}
if(userOptionsCBox[i].equalsIgnoreCase("useDB")) {
// append() argument is value of the value attribute belonging to the input attribute
params.append("useDB=1");
} else if(userOptionsCBox[i].equalsIgnoreCase("sendEmail")) {
params.append("sendEmail=1");
}
isFirst = false;
}
queryStringParams = params.toString();
}
if(userChoiceSelect.equals("1")) {
response.sendRedirect("ListCities.html" + queryStringParams);
} else if(userChoiceSelect.equals("2")) {
response.sendRedirect("AddCity.html" + queryStringParams);
} else if(userChoiceSelect.equals("3")) {
response.sendRedirect("DeleteCity.html" + queryStringParams);
} else {
response.sendRedirect("index.html");
}
}
}
index.html:
<html>
<head>
<title>Welcome to the City Manager</title>
</head>
</html>
<body>
<form id="form1" method="post"
action="/CityManagerWeb/mainmenuresponder.do">
<table style="width:100%">
<tr>
<td style="width:100%" align="center">
<h1>Welcome to the World City Manager</h1>
</td>
</tr>
<tr>
<td>
<h3>What would you like to do today?</h3>
</td>
</tr>
<tr>
<td>
<select id="menuChoice" name="menuChoice">
<option id="1" value="1">
List Cities
</option>
<option id="2" value="2">
Add a new city
</option>
<option id="3" value="3">
Delete a city
</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="adminoptions" id="optionDatabase" value="useDB" />Use Database<br>
<input type="checkbox" name="adminoptions" id="optionEmail" value="sendEmail" />Send Confirmation<br>
</td>
</tr>
<tr>
<td>
<input name="chooser" type="submit" value="Choose" />
</td>
</tr>
</table>
</form>
</body>
ListCities.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Listing Cities</title>
</head>
<body>
<table style="width:450px;">
<tr>
<td style="width:150px;"><b>COUNTRY</b></td>
<td style="width:300px;"><b>CITY</b></td>
</tr>
<tr>
<td>Russia</td>
<td>Moscow</td>
</tr>
<tr>
<td>England</td>
<td>London</td>
</tr>
<tr>
<td>United States</td>
<td>Washington, D.C.</td>
</tr>
</table>
</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" 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>CityManagerWebStarter</display-name>
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks for any suggestions/help.
A fairly common problem I'm seeing these days is that people are using the latest IDE tooling that generates their web projects using the Servlet 3.0 specification i.e. the files generated use the new #WebServlet, #WebFilter etc. annotations way of doing things against the traditional deployment descriptor web.xml. But, they follow these old Servlet 2.x tutorials online and end up configuring the same servlet twice; once with the annotations and once again in the web.xml. This would lead to your server responding in undefined ways and must be avoided.
So, you can safely get rid of the following from your web.xml:
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
The next issue is that your web application's context root is never a part of your servlet or filter's url-pattern. So, your annotation should be like
#WebServlet("/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
Lastly, though it works as is, your form's action attribute shouldn't hard code the context root like that. I suggest you use a relative URL there as well.
<form id="form1" method="post" action="mainmenuresponder.do">
Notice, that unlike the servlets, you can't put a leading / in the action here.
If citymanagerwebstarter is the content root. It should not be part of the url parttern in web.xml and #WebServlet annotation.

Eclipse - Java Issue finding the controller

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");
}
}

Categories