Submit form to servlet using JQuery Ajax - java

How can we submit Form to servlet when we click on span tag using Jquery Ajax, and get output from servlet?
Below is calculator example code.
If instead of span if i use input type="submit" i get the right result in index.html, but if i use span instead of input type for submit, i am directed to servlet page.
index.html
<form name="form1" method="POST" action="Ajaxexample" id="form1">
<table>
<tr>
<td>Number 1</td><td><input type="text" name="n1"/></td>
</tr>
<tr>
<td>Number 2</td><td><input type="text" name="n2"/></td>
</tr>
<tr>
<td></td><td><span onclick="form1.submit()">Calculate</span></td>
</tr>
<tr>
<td>Result</td><td><input type="text" value="" id="result"/></td>
</tr>
</table>
</form>
<script src="script/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var form = $('#form1');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: value,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
return false;
});
</script>
Ajaxexample.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));
out.println(n1 + n2 + "");
}
}
web.xml
<display-name>Ajax</display-name>
<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>
<servlet>
<servlet-name>Ajaxexample</servlet-name>
<servlet-class>Ajaxexample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajaxexample</servlet-name>
<url-pattern>/Ajaxexample</url-pattern>
</servlet-mapping>

<span onclick="formSubmit();">Calculate</span>
function formSubmit(){
$.ajax({
url:'localhost:8080/Ajax/Ajaxexample',
data: $("#form1").serialize(),
success: function (data) {
$('#result').html(data);
}
});
}

you form method is post <form name="form1" method="POST" action="Ajaxexample" id="form1"> but you are writing codes in servlet doGet() so you may not proper results.Remeber that if the form method is get then in the servlet doGet() will be called and if the form method is post then in servlet doPost() will be called

You have clearly written " onclick="form1.submit()">" that's why form is submitting....
Remove onClick() method from submit &
<span id="calc">Calculate</span
& replace
form.submit(function () {
line by
$( "#calc" ).click(function(){

Related

I am trying to call a servlet from a jsp file to do the business logic and return to the same page

i have my project structure as follows
here is my jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h2>Binary Search</h2>
<form action ="SearchServlet" method = "post">
<label>Enter size of the list</label>
<input type="text" name ="listSize"><br><br>
<label>Here is your Generated list...!!!</label><br><br>
<textarea rows="10" cols="50"><c:out value="${list}"/> </textarea><br><br>
<label>Enter number to search in the list</label>
<input type="text" name ="searchNumber"><br><br>
<button type="submit" name="button" value="generate">Generate List</button>
<button type="submit" name="button" value="search">Search Number</button>
<button type="reset" name="button" value="reset">Reset</button>
</form>
</body>
</html>
so when i click generate list button i am expecting it to redirect to my servlet and do my logic and return with arraylist to show it in text area.
here is my servlet
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
GenerateList newList = new GenerateList();
SearchList searchList = new SearchList();
String button = request.getParameter("button");
ArrayList<Integer> newGeneratedList = new ArrayList<Integer>();
if ("generate".equals(button)) {
newGeneratedList = newList.GeneratedList(Integer.parseInt(request.getParameter("listSize")));
request.setAttribute("list",newGeneratedList);
response.sendRedirect("index.jsp");
} else if ("search".equals(button)) {
}
//doGet(request, response);
}
}
but i get 404 not found error when click this.i have searched for hours and cannot find why,and i am still a beginner of servlet.any leads/help would be great.
here is my web.xml also
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SearchServlet</servlet-name>
<display-name>SearchServlet</display-name>
<description></description>
<servlet-class>SearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BinarySearchServlet</servlet-name>
<url-pattern>/binarySearchServlet</url-pattern>
</servlet-mapping>
You can use request dispatcher in place of sendRedirect in your servlet.
Try this:
RequestDispatcher rd=request.getRequestDispatcher(jspName);
rd.forward(request, response);
In parameter write your JSP name from where you have call this servlet.
forward function will redirect to you at your desired page.

Why if I press F5 the servlet session ends?

When I login from index.jsp, I can see the confirmation saying that the login was successful but if I press the F5 button the previous session is not considered and new session is created... so I have to login again and again if I press F5...
How can I make the session persistent?
index.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%# page session="true"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title> Practica3 </title>
<link rel="stylesheet" type="text/css" href="css/structure.css" />
<script type="text/javascript" src="jquery/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".menu").click(function(event) {
$('#content').load('Content',{content: $(this).attr('id')});
});
});
</script>
</head>
<body>
<!-- Begin Wrapper -->
<div id="wrapper">
<!-- Begin Header -->
<div id="header">
This is the Header
</div>
<!-- End Header -->
<!-- Begin Navigation -->
<div id="navigation">
<jsp:include page="menu3.jsp" />
</div>
<!-- End Navigation -->
<!-- Begin Faux Columns -->
<div id="faux">
<!-- Begin Left Column -->
<div id="leftcolumn">
</div>
<!-- End Left Column -->
<!-- Begin Content Column -->
<div id="content">
<jsp:include page="login.jsp" />
</div>
<!-- End Content Column -->
<!-- Begin Right Column -->
<div id="rightcolumn">
</div>
<!-- End Right Column -->
</div>
<!-- End Faux Columns -->
<!-- Begin Footer -->
<div id="footer">
This is the Footer
</div>
<!-- End Footer -->
</div>
<!-- End Wrapper -->
</body>
</html>
menu.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<script type="text/javascript">
$(document).ready(function() {
$(".menu").click(function(event) {
$('#content').load('Content',{content: $(this).attr('id')});
});
});
</script>
<%HttpSession session = request.getSession(true);
System.out.println("cargamos menu.jsp");
System.out.println(" (menu.jsp)Sesion:"+session);
System.out.println("Sesion(user):"+session.getAttribute("user"));
if ((session != null) && (session.getAttribute("user")!=null)) {
%>
<table>
<tr>
<td> <a class="menu" id="logout.jsp" href=#> Logout </a> </td>
</tr>
</table>
<% }
else {%>
<table>
<tr>
<td> <a class="menu" id="form.jsp" href=#> Registration </a> </td>
<td> <a class="menu" id="login.jsp" href=#> Login </a> </td>
</tr>
</table>
<%}; %>
login.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="models.BeanLogin" %>
<script type="text/javascript" src="jquery/jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#registerForm").validate({
submitHandler: function(form) {
$('#content').load('logincontroller',$("#registerForm").serialize());
}
});
}
);
</script>
</head>
<body>
<%
BeanLogin login = null;
if (request.getAttribute("login")!=null) {
login = (BeanLogin)request.getAttribute("login");
}
else {
login = new BeanLogin();
}
%>
<form id=registerForm action="/Practica3/logincontroller" method="POST">
<table>
<tr>
<td> User id </td>
<td> <input type="text" name="user" value="<%=login.getUser() %>" id="user" class="required" minlength="5"/> </td>
<%
if ( login.getError()[0] == 1) {
%>
<td class="error"> Invalid username or password. </td>
<%
}
%>
</tr>
<tr>
<td> Password </td>
<td><input type="password" name="password" placeholder="Password"
value="<%=login.getPassword()%>" id="password" class="required" minlength="8" /></td>
</tr>
<tr>
<td> <input name="submit" type="submit" value="Enviar"> </td>
</tr>
</table>
</form>
loginOk.jsp:
<script type="text/javascript">
$(document).ready(function() {
$('#navigation').load('menu.jsp');
});
</script>
Logged in!
loginController.jsp:
/**
* Servlet implementation class logincontroller
*/
public class logincontroller extends HttpServlet {
private static final long serialVersionUID = 1L;
private static DAO Dao;
/**
* #throws Exception
* #see HttpServlet#HttpServlet()
*/
public logincontroller() throws Exception {
super();
Dao = new DAO();
// 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
BeanLogin login = new BeanLogin();
BeanUtilities.populateBean(login, request);
try {
if (login.isComplete() && checkLogin(login)) {
HttpSession session = request.getSession();
session.setAttribute("user",login.getUser());
System.out.println("Se ha hecho el login."+session.toString());
System.out.println("User:"+session.getAttribute("user"));
session.setMaxInactiveInterval(10);
RequestDispatcher dispatcher = request.getRequestDispatcher("loginOk.jsp");
if (dispatcher != null) dispatcher.forward(request, response);
} else {
request.setAttribute("login",login);
RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
if (dispatcher != null) dispatcher.forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #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);
}
protected boolean checkLogin(BeanLogin bean) throws SQLException{
String query = "SELECT id,password FROM ts1.users;";
ResultSet rs = Dao.executeQuerySQL(query);
while(rs.next()){
if (rs.getString(1).equals(bean.getUser()) && rs.getString(2).equals(bean.getPassword())){
return true;
}
}
int[] errors = bean.getError();
errors[0]++;
bean.setError(errors);
return false;
}
}
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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Practica3</display-name>
<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>
<servlet>
<description></description>
<display-name>Content</display-name>
<servlet-name>Content</servlet-name>
<servlet-class>controllers.Content</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Content</servlet-name>
<url-pattern>/Content</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>formcontroller</display-name>
<servlet-name>formcontroller</servlet-name>
<servlet-class>controllers.formcontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formcontroller</servlet-name>
<url-pattern>/formcontroller</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>logincontroller</display-name>
<servlet-name>logincontroller</servlet-name>
<servlet-class>controllers.logincontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logincontroller</servlet-name>
<url-pattern>/logincontroller</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>closesession</display-name>
<servlet-name>closesession</servlet-name>
<servlet-class>controllers.closesession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>closesession</servlet-name>
<url-pattern>/closesession</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>logoutcontroller</display-name>
<servlet-name>logoutcontroller</servlet-name>
<servlet-class>controllers.logoutcontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logoutcontroller</servlet-name>
<url-pattern>/logoutcontroller</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
</web-app>
The method setMaxInactiveInterval() accepts time as seconds. You are setting the maximum inactive time for the session to 10 seconds. Set it to a time more than that.
I assume that you press F5 on the page that loginController forwards to, which is supposed to be loginOK.jsp. And you might think that you refreshed the page loginOK.jsp, which is absolutely not. In fact, you just refreshed the loginController servlet.
The reason is that in your loginController, you use forward instead redirect. The url on your browser when your loginOK.jsp shows up is still loginController instead of loginOK.jsp. When you refresh this page, loginController gets refreshed. As a result a fresh request is created for loginController, a new login object is created. When you check/validate that login object in your loginController, it will fail the check/validation. Therefore, loginController forwards to login.jsp by your else statement.
One possible solution is to use redirect instead of forward:
response.sendRedirect(...);
However, I suggest that you redesign the login flow following the MVC pattern and do not put java snippet/code in your jsp page.
Good luck.

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

servlet returning blank page

i m trying to create a registration page in servlet..using tomcat 7 with eclipse, it returning blank page, i have tried available steps but no go.. please help....
here is JSP page
<form method="post" action="mbregistrationservlet">
First Name: <input type=text name=firstfame><br>
Last Name: <input type=text name=lastname></br>
Gender: <input type="radio" name="gender" Value="Male" checked>Male
<input type="radio" name="Gender" Value="Female">Female</br>
E-mail: <input type="email" name="email"><br>
Password:<input type="password" name="password"><br>
Security Question<select name="securityquestion">
<option value="Name of your first pet">Name of your first pet</option>
<option value="Name of your first byke">Name of your first byke</option>
<option value="Name of your first car">Name of your first car</option>
<option value="Name of your first school">Name of your first school</option>
<option value="Name of your first GF/BF">Name of your first GF/BF</option>
</select><br>
Answer: <input type="text" name="answer"><br>
Telephone:<input type="text" name="telephone"><br>
Address:<input type="text" name="address"><br>
City:<input type="text" name="city"><br>
State:<input type="text" name="state"><br>
Country:<input type="text" name="country"><br>
<input type="submit" value="suuubmit" name="Submit">
</form>
Servlet page
public class mbregistrationservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static boolean register(String firstname, String lastname, String gender,String email, String password, String securityquestion, String answer, String telephone, String address, String city, String state, String country) throws IOException
{
HttpServletResponse response = null;
//response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean x =false;
try{
/*dbconn obj=new dbconn();*/
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","******","*******");
PreparedStatement ps = con.prepareStatement("insert into mbregistration values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.setString(3,gender);
ps.setString(4, email);
ps.setString(5, password);
ps.setString(6, securityquestion);
ps.setString(7, answer);
ps.setString(8, telephone);
ps.setString(9, address);
ps.setString(10,city);
ps.setString(11,state);
ps.setString(12,country);
int i = ps.executeUpdate();
if (i>0){
x=true;
}
out.print("registered succcessfully");
//out.close();
}
catch(Exception e)
{
out.print("error");
//out.close();
}
return x;
}
XML page
<display-name>MobileWorld</display-name>
<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>
<servlet>
<description></description>
<display-name>mbloginservlet</display-name>
<servlet-name>mbloginservlet</servlet-name>
<servlet-class>mbworld.mbloginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mbloginservlet</servlet-name>
<url-pattern>/mbloginservlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Validate</display-name>
<servlet-name>Validate</servlet-name>
<servlet-class>mbworld.Validate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>success</display-name>
<servlet-name>success</servlet-name>
<servlet-class>mbworld.success</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>success</servlet-name>
<url-pattern>/success</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>mbregistrationservlet</display-name>
<servlet-name>mbregistrationservlet</servlet-name>
<servlet-class>mbworld.mbregistrationservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mbregistrationservlet</servlet-name>
<url-pattern>/mbregistrationservlet</url-pattern>
</servlet-mapping>
please let me know if i m doing something wrong.......
First of all you have to write your code in doPost method and the second thing is that if you are not using rd.forward(request,response) after RequestDispatcher rd=request.getRequestDispatcher("Name of page you want to redirect"); it will be a blank page after you click submit button.
so it should be like:
RequestDispatcher rd=request.getRequestDispatcher("Welcome");
rd.forward(request,response);
Change your method name as doPost instead of register (without static keyword) and from there using http servlet request access form fields using getParameter api. so it looks like:
public class mbregistrationservlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstfame");
//and so on
}
I don't see a doPost() method in the servlet, which is actually going to be called by the service method when you submit your form.
structure of doPost() method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
Corrections
You are not going to get input fields via parameters as you are expecting with you register method
public static boolean register(...)
morever this is illegal.
In,Order to get your input field parameters user Enumeration params = request.getParameterNames() which will return an Enumeration of all the parameters and via request.getParameterValue(params.nextElement()) you can access value corresponding to the input field specified by params.nextElement().
EXAMPLE.

Categories