How to call servlet file from html [duplicate] - java

This question already has answers here:
How to call servlet class from HTML form
(2 answers)
Closed 7 years ago.
How to call servlet file from html.I tried but when i click on submit its not taking any action,I am not getting any error also. and i want to submit data in database.action event is not working.Please help me
HTML code
<form name="form" method="post" action="NewServlet" >
<label for='name' ><font size="2">Your Full Name*: </label><br/>
<input type='text' name='name' id='name' maxlength="50" style="height:30px; width :250;" placeholder="Enter Full Name"/><br/><br/>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' maxlength="50" style="height:30px; width :250;" placeholder="Enter your Email"/><br/><br/>
<label for='phone' >Phone Number*:</label><br/>
<input type='text' name='phone' id='phone' maxlength="15" style="height:30px; width :250;" placeholder="Enter Phone Number"/><br/><br/>
<label for='Reason' >Reason*:</label><br/>
<select name="reason" style="height:30px; width :250;">
<option>Select</option>
<option>Enquiry</option>
<option>Complain</option>
<option>Order</option>
</select>
</br>
</br>
</br>
<label for='message' >Address Or Message:</label><br/>
<textarea style="height:100px; width :400;" name='message' id='message' placeholder="Enter Address or Message"></textarea></p>
</b>
</size>
<%--
<input type='submit' name='btnSubmit' value="Submit"/>
--%>
<img src="Image/submit1.png" style="width:150px; height:70px;top:50%px; " onmouseover="this.src='Image/submit2.png'" onmouseout="this.src='Image/submit1.png'"/>
</form>
Servlet code
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String driver= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://localhost:1433;databaseName=wristwatch; username=sa; password=abc#123;";
try {
//int id=Integer.parseInt(request.getParameter("txt_id"));
String nm=request.getParameter("name");
String email=request.getParameter("email");
int phone=Integer.parseInt(request.getParameter("phone"));
String reason=request.getParameter("reason");
String add=request.getParameter("Address");
Class.forName(driver);
Connection c=DriverManager.getConnection(url);
out.println("Data Inserted");
}
catch(Exception e)
{
System.out.print(e);
}
finally {
out.close();
}
}
web.xml
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>

Change the processRequest(...){...} to doPost(...){...} in servlet.
This link might make you clear.
ProcessRequest Method

Related

Post Form won't call Servlet

So i have a post form which calls a Servlet to perform a search but the problem is that when i push the submit button it's completely unresponsive. Although when used in the same form in a different .jsp page it works as it should. If it had something to do with the servlet mapping there would be an error page from the tomcat server but i do not get such an error page. It's just completely unresponsive.
My HTML form:
<form action="AnonSearchServlet" class="form-inline" method="post">
<input type="search" name="location" class="form-control input-lg" placeholder="Destination, City, Address" required>
<div class="input-group">
<input type="search" class="form-control input-lg" placeholder="When" name="daterange" value="" required/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
<input style="width: 20%; height: 46px" type="number" min="1" name="accomodates" class="form-control" placeholder="Guests" required>
<button type="submit" class="btn btn-danger btn-lg">Search</button>
</form>
My Servlet:
public class AnonSearchServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start_date;
String end_date;
String date_range = request.getParameter("daterange");
UserBean user = new UserBean();
String[] tokens = date_range.split(" ");
start_date = tokens[0];
end_date = tokens[2];
try {
HttpSession session = request.getSession(true);
user.setUserID(0);
System.out.println(user.getUserID());
ResultSet search_rs = null;
SearchBean search_bean = new SearchBean();
search_bean.setUserId(user.getUserID());
search_bean.setLocation(request.getParameter("location"));
System.out.println(request.getParameter("location"));
search_bean.setStreet(request.getParameter("location"));
search_bean.setNeighbourhood(request.getParameter("location"));
search_bean.setAccomodates(request.getParameter("accomodates"));
search_bean.setStartDate(start_date);
search_bean.setEndDate(end_date);
search_bean = SearchDAO.search(search_bean);
session.setAttribute("current_search", search_bean);
response.sendRedirect("searchResults.jsp");
} catch (Throwable thException) {
System.out.println(thException);
}
}
}
And my web.xml:
<servlet>
<servlet-name>AnonSearchServlet</servlet-name>
<servlet-class>Servlets.AnonSearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AnonSearchServlet</servlet-name>
<url-pattern>/AnonSearchServlet</url-pattern>
</servlet-mapping>
#CharisAlex here is the problem in your jsp page <button> tag doesn't submit form action so you have to modify your code
<button type="submit" class="btn btn-danger btn-lg">Search</button>`
replace into
<input type='submit' class='btn btn-danger btn-lg' value="Search" />
Try to use
<input type="submit" value="submit">
instead of using
<button type="submit" class="btn btn-danger btn-lg">Search </button>

Java Servlet not receiving values from JSP Form

This is my first time setting up a Java Servlet, I am trying to retrieve values into my Java Servlet from my input fields in my JSP Form when the user clicks a specific button. I also, am unsure if I used the proper practice for creating my Servlet. I simply right-clicked on my Apache Tomcat 8.0 server and then selected new Servlet.
Java Servlet:
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Your request attribute's name are uname and psw which are added on Jsp page. So you must change your doPost method like this.
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Or
You must change your form in jsp page like this:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

Reading table html rows values to a servlet to another jsp page for editing

I want to get the values for the rows which is then sent to a Java servlet then read by another page and inserts those values into the text boxes for the user to edit and write it back into the text file.
So it gets read by ProductIO which reads the textfile.
Its then entered into a jsp table
<c:forEach var="product" items="${products}">
<tr>
<td ><c:out value='${product.code}'/></td>
<td ><c:out value='${product.description}'/></td>
<td >${product.priceCurrencyFormat}</td>
<td><form action="editproduct" method="post">
<input type="submit" value = "Edit">
</form>
</td>
<td><form action="deleteproduct" method="post">
<input type="submit" value = "Delete">
</form>
</td>
</tr>
</c:forEach>
The User Clicks either the delete or edit button which will then send action to either the deleteproduct servlet or the editproduct servlet(only asking about the edit for now)
The edit product servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String url = "/editproduct.jsp";
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
String action = request.getParameter("action");
if (action == null) {
action = "editproduct"; // default action
} else if (action.equals("editproduct")) {
String productCode = request.getParameter("productCode");
String descString = request.getParameter("description");
//HttpSession session = request.getSession();
Product product = (Product) session.getAttribute("cart");
if (product == null) {
product = new Product();
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
Which the three Values are put into three text boxes on the editProduct.jsp page(where im having a problem getting the values to insert into the text boxes for it to be written back to the text file with the new information)
<form action="Product" method="post" >
<input type="hidden" name="action" value="add">
<label>Code:</label>
<input type="text" name="code" value='<%=request.getAttribute("code")%>'
required><br>
<label >Description:</label>
<input type="text" name="desc" value='<%=request.getAttribute("description")%>'
required ><br>
<label >Price:</label>
<input type="text" name="price" value='<%=request.getAttribute("price")%>'
required ><br>
<label> </label>
<!--<input type="submit" value="Update Product" class="margin_left">-->
<!--<input type="submit" value="View Product" class="margin_left">-->
<button type="submit">Update</button><br>
I can share more code if needed.
You aren't calling request.setAttribute() with any of the attributes in your Servlet. I assume you meant to add something like
request.setAttribute("code", productCode);
request.setAttribute("description", descString);
request.setAttribute("price", product.getPrice());
Before forwarding the request.

perform a servlet doPost from jsp form file

I'm new to servlets and jsp files, and I encountered the following problem:
I have the following jsp form file:
<FORM action="http://myApp/register" method="post">
<P>
First name: <INPUT type="text" name="firstname"><BR>
Last name: <INPUT type="text" name="lastname"><BR>
email: <INPUT type="text" name="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
and a servlet which handles a doPost request on the url above.
I want to give the values of the form (such as the first name and last name) to the doPost request.
Any ideas?
Thanks a lot! :)
You can get all the parameters by their name as request.getParameters("firstname") to get the value of the input fields.
public class ServletClass extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastName");
// and so on.....
}
}

Gettin Edit Value from index.jsp

I am newbie in HTML and Servlets. I have such a idex.jsp contents:
<form action="createCSV" method="get">
<input type="text" value="D:/">
<input type="submit" value="create">
</form>
And I want to use value of <input type="text" value="D:/"> inside of method Get in my Servlet:
protected void doGet( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response )
throws javax.servlet.ServletException, IOException{}
Please, help me
change the input field in your html form like this:
<input type="text" name="userInput" value="D:/">
inside the servlet do that:
String userInput = request.getParameter("userInput");

Categories