Index.jsp
<form method="post" action="serv">
Enter Latest Reading <input type="text" name="t1"> <br>
Enter Previous Reading <input type="text" name="t2"> <br>
<input type="submit" value="SEND">
</form>
LoginServlet.java
#WebServlet("/serv")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<u>Following are your Bill Particulars</u><br><br>");
req.setAttribute("unitRate", new Double(8.75));
req.getRequestDispatcher("/Test").include(req, res);
out.println("<br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection");
out.close();
}
}
IncludeServlet.java
#WebServlet("/Test")
public class IncludeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
int latestReading = Integer.parseInt(req.getParameter("t1"));
int previousReading = Integer.parseInt(req.getParameter("t2"));
Object obj = req.getAttribute("unitRate");
Double d1 = (Double) obj;
double rate = d1.doubleValue();
int noOfUnits = latestReading-previousReading;
double amountPayable = noOfUnits * rate;
out.println("Previous reading: " + previousReading); out.println("<br>Current reading: " + latestReading);
out.println("<br>Bill Amount Rs." + amountPayable);
}
}
When I run the above project, only the response of LoginServlet is displayed in a browser, I'm unable to include the response of IncludeServlet.java.
All System.out.println("") of LoginServlet is being display is console only, non from IncludeServlet.
I also use debugger, but this is not going into IncludeServlet.java page.
In your IncludeServlet instead of overriding doGet method override doPost , Since Post request is coming from HTML
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// do Whatever you want to do .
}
Update: Also write res.setContentType("text/html"); in both servlet so that your html written in out.print executes otherwise your output will look like <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection.
Related
In mydemo.java I have this code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
JsonObject person = new JsonObject();
person.addProperty("firstName", "Andrew");
person.addProperty("lastName", "Coolins");
person.addProperty("address", " xx september");
String person= request.getParameter("firstname");
and my output for json string is:
{"firstName":"Andrew","lastName":"Coolins","address":" xx september"}
In mydemo2.java in method post, I want to add something like this:
String jsonobj= request.getParameter("firstname"); //for example
request.setAttribute("firstname", firstname); //for example
request.getRequestDispatcher("index.jsp").forward(request, response);
My question is, how can I retrieve values for example "firstname" of json obj from a form in my index.jsp when the user insert data for firstname and then clicks on submit button? Can you explain to me with code?
For example, you can add something like this to your jsp page
<form method=post action =someServlet>
<input type="text" name="firstname"/>
<input type=submit value="Do something"/>
</form>
Then in your servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String firstname = request.getParameter("firstname");
//do something
}
I didn’t fully understand the question, did you ask about this?
I have a .jsp page that lists all of my employees from a database. Next to each employee you can click on the button edit or delete, which will add an id of that employee into url param:
<%
List<Employee> employees = (List<Employee>) request.getAttribute("employees");
if (employees != null)
for (Employee employee : employees) {
%>
<tr>
<td><%=employee.getId()%></td>
<td><%=employee.getName()%></td>
<td><%=employee.getSurname()%></td>
<td><%=employee.getRegistrationDate()%></td>
<td>edit</td>
<td>delete</td>
</tr>
<%
}
%>
When I click on 'delete', the listing is being deleted straight away and I get immediately redirected back to the list of my employees, it works well.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = (int) request.getAttribute("id");
EmployeeDAO.deleteEmployee(id);
response.sendRedirect("EmployeeServlet");
}
When I click on 'edit', I see te .jsp that has the url with the correct id and it asks me to provide new name and surname of my employee:
<form action="UpdateEmployeeServlet" method="post">
Name <input type="text" name="name"><br>
Surname <input type="text" name="surname"/><br>
<input type="submit"value="Save">
Once i click 'save', I get NullPointerException. It seems like it cannot get or parse the id parameter. Where is an error in my UpdateEmployeeServlet methods?
#WebServlet("/UpdateEmployeeServlet")
public class UpdateEmployeeServlet extends HttpServlet {
public UpdateEmployeeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Employee employee = EmployeeDAO.getEmployeeById(id);
request.getRequestDispatcher("updateemployee.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Employee employee = new Employee((int) request.getAttribute("id"), request.getParameter("name"),
request.getParameter("surname"), Date.valueOf(request.getParameter("registration_date")));
int status = EmployeeDAO.updateEmployee(employee);
request.getRequestDispatcher("employeelist.jsp").forward(request, response);
}
}
Integer.parseInt tries to convert a String to an Integer and will throw an Exception if it fails to do so. Since you get a NullPointerException, it is clear that request.getParameter("id") is null. The reason of this is that your form does not contain any items with the name of id. Try to add a hidden input to the form there with name="id" and the correct value. It should solve your problem.
Doing form handling with Servlets is really low-level and there is no need to reinvent the wheel. You should consider using Spring MVC which has excellent support for form handling.
Having said that check the parameters of your <form>. You are handing over name, surname and submit to doPost(). There is no id given. Furthermore as pointed out already you are using request.getAttribute("id") instead of request.getParameter("id").
You could set your object to request scope in your doGet()-method: request.setAttribute("employee", employee). You would then access the fields of this object in your JSP. Add this to your form: <input type="hidden" value="${requestScope.employee.id}"/>. You should also mask your IDs (e.g. HashIds) and read about CSRF
So this is the code i'm using to send the parameter "idemp" that contains the value ${masession.idemp}
<a href="<c:url value="/consultertickets">
<c:param name="idemp" value="${masession.idemp}"/>
</c:url>">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
when redirected to the servlet "/consultertickets" the browser URL shows:
http://localhost:4040/monprojet2/consultertickets?idemp=64
so the parameter is passed and working but the method used to obviously GET and not POST, which is the method i'm using in the servlet, here's the servlet's code.
#WebServlet(urlPatterns= {"/consultertickets"})
public class ConsulterTickets extends HttpServlet {
private String VUE = "/WEB-INF/ListeTickets.jsp";
#EJB
private TicketDao ticketDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
List<Ticket> lticket = ticketform.recupererTickets(request);
boolean resultat;
if(lticket.isEmpty())
{
//resultat="Vous n'avez soumit aucun ticket";
resultat = false;
request.setAttribute("resultat", resultat);
this.getServletContext().getRequestDispatcher("/ListeTickets2.jsp").forward(request, response);
}else{
//String VUE = "/ListeTickets.jsp";
resultat=true;
request.setAttribute("resultat", resultat);
request.setAttribute("lticket", lticket);
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
}
}
is there any way to pass a parameter to a servlet through POST method, without going through the <form></form>
Solution 1:
Modifying doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
doPost(request, response);
}
Solution 2:
Remove the doGet() and change doPost() to service()
Edit1:
See, Hyperlinks(<a> tag) are meant to send GET request but not POST.
So, if you want to achieve sending POST request using Hyperlink there is no straight way. But, Javascript can be your help.
Using Javascript you can guide <a> to send POST request along with the help of <form>.
I just modified your code little bit. This should help you.
<a href="javascript:document.getElementById('form1').submit()">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
<form action="<c:url value="/consultertickets"/>" method="post" id="form1">
<input type="hidden" name="idemp" value="${masession.idemp}"/>
</form>
I have this code and I'm having the null pointer error, this is suppose to get the name of the submit and act in consequence but it only gets null.
Here is the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String peticion=request.getParameter("Submit");
ServletContext sc=getServletContext();
RequestDispatcher rd;
switch(peticion){
case "registrar":
rd=sc.getRequestDispatcher("/CreaVotante");
rd.forward(request,response);
break;
}
Here is the submit line:
<input type="Submit" name="registrar" value="Regístrate para votar">
The submit is into a form.
With your form example, the way to extract the parameter would be
String param=request.getParameter("registrar");
<form method="post" action="RegisterServletPath">
Name:<input type="text" name="userName"><br>
Password:<input type="password" name="password"><br>
Email Id:<input type="text" name="email"><br>
Language: <select name="language">
<option>Hindi</option>
<option>English</option>
<option>French</option>
</select> <br>
<input type="submit" value="Submit">
</form>
after submitting the form the following error occur
HTTP Status 405 - HTTP method GET is not supported by this URL
here is my java class. i have defined only post method and called post method in html form
public class RegisterServlet 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("password");
String e = request.getParameter("email");
String c = request.getParameter("language");
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/eclipse/register.accdb","","");
PreparedStatement ps = con.prepareStatement("insert into USERDETAILS values(?,?,?,?)");
ps.setString(1, n);
ps.setString(2, p);
ps.setString(3, e);
ps.setString(4, c);
int i= ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
}
//... not relevant here
}
}
web.xml
<display-name>SimpleServletProject</display-name>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>org.venkatesh.Servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServletPath</url-pattern>
</servlet-mapping>
add the rest of the servlet code, I think you are either using doGet method and calling super.doGet from it, or not using doGet but unfortunatly the doGet method in HttpServlet is being called.
Here comes another problem! from where the doGet method in either case is being called?
If you can't find where, then try adding
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
this should solve the problem, if it doesn't then let me know if all my assumptions are wrong.