<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>
Related
This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 2 years ago.
I have read all the questions about this here, but I still do not have any progress. I want to pass the value from the input field to my servlet, but the servlet's request.getParameter returns null, instead of what is inputted. Here is my HTML:
<form method="post" action="MyHttpServletDemo" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
</form>
<button type="button" id="vnes" onclick="Vnes()">Search</button>
Here is my .xml:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
And the Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
I tried this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
HTML:
<form method="post" action="/welcome" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
<button type="button" id="vnes" onclick="Vnes()">Search</button>
</form>
And still does not work.
It worked! Here's the solution:
HTML:
<form method="get" action="welcome" id="myForm">
<input type="text" id="pole" name="pole1" placeholder=" Input coordinates...">
<button type="submit" id="vnes">Search</button>
</form>
.xml file:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("pole1");
out.println("<h1>" + value + "</h1>");
}
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 have home page and when I click on reference Servlet don't work and I get error 404. I think issue in web.xml mapping, but a don't understand where. Please help me correct this issue. Thank you.
My web.xml
<!--Homepage.-->
<servlet>
<servlet-name>HomePageServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.HomePageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomePageServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--Add user in database.-->
<servlet>
<servlet-name>AddUserServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.AddUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddUserServlet</servlet-name>
<url-pattern>/addition</url-pattern>
</servlet-mapping>
My jsp homepage:
<body>
<ul>
<li>addition</li>
</ul>
</body>
And servlet with doGet method for it:
public class HomePageServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF8");
req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
}
}
And by http://localhost:8080/items/ I get my home page.
But, when I click on reference from index.jsp, return: HTTP Status [404] – [Not Found]
My addition.jsp same lie in /WEB-INF/views/addition.jsp
My Servlet for work with addition.jsp :
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
db.getDBExecutor().addUser(
new User(req.getParameter("name"),
req.getParameter("login"),
req.getParameter("email")));
req.setAttribute("serverAnswer", "Add ok!");
req.getRequestDispatcher("/WEB-INF/views/answer.jsp").forward(req, resp);
}
}
And addition.jsp:
<body>
<form method="post" action="addition">
<input type="text" required placeholder="name" name="name"><br>
<input type="text" required placeholder="login" name="login"><br>
<input type="text" required placeholder="email" name="email"><br>
<input type="submit" value="add">
</form>
</body>
I would suggest to use try/catch and debugger mode.
And try to use like this your getRequestDispatcher
request.getRequestDispatcher("answer.jsp").forward(request, response);
or
req.getRequestDispatcher("~/WEB-INF/views/answer.jsp").forward(req, resp);
I think you need to get parameter for each of one, and than set. Try this;
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
String Name = request.getParameter("name");
String Login= request.getParameter("login");
String Email= request.getParameter("email");
db.getDBExecutor().addUser(
new User(Name, Login, Email);
//And you need to 'serverAnswer' item in your 'answer.jsp' you know.
request.setAttribute("serverAnswer", "Add ok!");
request.getRequestDispatcher("answer.jsp").forward(req, resp);
}
}
And then you can use getAttribute like this in your answer.jsp,
<%String Answer= (String)request.getAttribute("serverAnswer"); %><%= Answer%>
Don't blame me, just i wanna help to you, i hope so it can be help to you, if you wanna you can look my trial project; https://github.com/anymaa/GNOHesap
Have a nice coding :)
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.
This is my Login.jsp page
<form name="login" action="ValidateServlet" method="post">
<input type="hidden" name="pagename" value="login"/>
<table>
<tr>
<td><b>USERNAME:</b><input type="text" name="txtUsername"/> </td>
</tr>
<tr>
<td><b>PASSWORD:</b><input type="password" name="txtPassword"/></td>
</tr>
<tr>
<td><input type="SUBMIT" value="SIGN IN"/></td>
</tr>
<tr>
<td>Forgot Password</td>
</tr>
<tr>
<td> Create New user </td>
</tr>
</table>
</form>`
And this is my SignupServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
}
and this is my web.xml
<servlet>
<servlet-name>SignupServlet</servlet-name>
<servlet-class>com.affiliate.servlet.SignupServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupServlet</servlet-name>
<url-pattern>/SignUp</url-pattern>
</servlet-mapping>
Login.jsp is in Webcontent/WEB-INF/WebPages/Login.jsp
and SignupServlet in JavaResources/src/com.affiliate.servlet/SignupServlet
but my Login is not redirecting to the SignupServlet. And i have doubt on my href and form action. Please help me in this regard.
Change
Create New user
↑
To
Create New user
And in anchor tag there is no post method available. You need to change the code in SignupServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException
{
RequestDispatcher rd = request.getRequestDispatcher("Signup.jsp");
rd.forward(request, response);
}
If you want post request using a tag then refer POST from an tag
replace
Forgot Password
Create New user
To
Forgot Password
Create New user
Remove "/" before Servlet URL Pattern
Change this code
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
to
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
getServletContext().getRequestDispatcher("WEB-INF/WebPages/Signup.jsp").forward(request, response);
}
In your login.jsp call SignUp servlet in following way
<td> Create New user </td>
and In SignUp servlet in your doGet method
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/webpages/Signup.jsp");
rd.forward(request, response);
Because when you call a servlet from a link or href it the doGet method gets run. Hope this helps