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.
Related
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.
I am trying to read certain values from web.xml file and I am getting the error in the image at the bottom of this question.
Config.html
<form action="go" method="get">
Enter name:<input type="text" name="pname"><br>
Enter Age:<input type="text" name="page"><br>
<input type="submit" value="submit">
</form>
UseServletContext.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter pw=response.getWriter();
//Read form data through Form Page:
String name=request.getParameter("pname");
String age=request.getParameter("page");
//Approach1
ServletConfig cg=getServletConfig();
ServletContext sc=cg.getServletContext();
String db2url=sc.getInitParameter("db2url");
String db2user=sc.getInitParameter("db2user");
String sql="insert into jalajclients(name,age) values(?,?)";
//Convert age to numeric values.
int age1=Integer.parseInt(age.trim());
//Store these Values to the DataBAse.
try {
Class.forName("com.ibm.db2.jcc.Db2Driver");
Connection con=DriverManager.getConnection(db2url,db2user,"786");
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setInt(2, age1);
int i=ps.executeUpdate();
pw.println(i);
} catch(Exception e) {
e.printStackTrace();
}
}
I am getting the following error:
web.xml
<servlet>
<description></description>
<display-name>UseServletContext</display-name>
<servlet-name>UseServletContext</servlet-name>
<servlet-class>UseServletContext</servlet-class>
</servlet>
<context-param>
<param-name>db2url</param-name>
<param-value>jdbc:db2://localhost:50000/mydb1235</param-value>
</context-param>
<context-param>
<param-name>db2user</param-name>
<param-value>piyush</param-value>
</context-param>
<servlet-name>UseServletContext</servlet-name>
<url-pattern>/go1</url-pattern>
</servlet-mapping>
Can anyone guide me what I am doing wrong?
Did you override the init method in your Servlet?
If yes, then don't forget to call super.init(config);in it like below
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
<form id='search' method='get'>
<input type='text' name='search' />
<input type='submit' value='Search'/><br/>
</form>
I have this search form.
String search = request.getParameter("search");
if (search != null) {
request.setAttribute("search", search);
RequestDispatcher rd = request.getRequestDispatcher("Content");
rd.forward(request, response);
}
And here I want to get what I type in the input and dispatch it to the Content. My input is not reaction at all. My debugger shows that my programm doesnt even go to the request.getParameter("search") part. Whats the problem?
Specify the action name in form like below:
<form action="/yourServlet/"id='search' method='get'>
<input type='text' name='search' />
<input type='submit' value='Search'/><br/>
</form>
Servlet Code:
public class YourServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException{
String search = request.getParameter("search");
if (search != null) {
request.setAttribute("search", search);
RequestDispatcher rd =
request.getRequestDispatcher("Content");
rd.forward(request, response);
}
}
}
And servlet mapping in your web.xml:
<servlet>
<servlet-name>yourServlet</servlet-name>
<servlet-class>test.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>yourServlet</servlet-name>
<url-pattern>/yourServlet/</url-pattern>
</servlet-mapping>
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");
}
}
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(){