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");
Related
When I access "http://localhost:8080/project/Song", dont appears any error, it works it lists some songs in the page. When I click on a song I go to a URL "http://localhost:8080/SongPage?name=A+Tribe&id=201" but here it appears a 404 error, maybe because the url has parameters, accessing this URL appears an error:
HTTP Status 404 – Not Found
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Do you know why?
Maybe its because of this urlPattern below:
#WebServlet(name ="SongPage", urlPatterns = {"/SongPage"})
I have this servlet below:
#WebServlet(name ="Song", urlPatterns = {"/Song"})
public class Song extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
QueryManager qm = new QueryManager();
ArrayList<ArrayList<String>> result = qm.Songs();
qm.closeConnections();
request.setAttribute("result", result.get(0));
request.setAttribute("id", result.get(1));
RequestDispatcher view=request.getRequestDispatcher("songList.jsp");
view.forward(request,response);
}
}
In songList.jsp i have this:
<c:forEach items="${result}" var="item" varStatus="status">
${result[status.index]} <br />
</c:forEach>
SongPage.java:
#WebServlet(name ="SongPage", urlPatterns = {"/SongPage"})
public class SongPage extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name").replace("+"," ");
...
}
Your original url "http://localhost:8080/project/Song" has "project" as base path but the other url "http://localhost:8080/SongPage?name=A+Tribe&id=201" does not have that path. Most likely you need to update your JSP to include it in the "href" tag as a quick fix:
${result[status.index]} <br />
or most likely if it is actually a context path:
${result[status.index]} <br />
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>
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.
I want when my page such as index.jsp loading(calling get method) send data for index.jsp page such as title. I checked this question but this question solution(How to call servlet on jsp page load) has error in my web application.
This my index.jsp page code(I want send title from changeTitle.java class):
<title><c:import url="/sysAdmin/changeTitle.java" />
<c:out value="${message }"></c:out></title>
This my changeTitle.java class get method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("message", "hello");
}
And I don't know how addressing to class in index.jsp of my project and bellow is my project directories:
Try setting the response, not the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setAttribute("message", "hello");
}
Try using this code:
<c:out value="<%=request.getAttribute('message')%>">
I am trying to implement a simple login servlet but it's not working properly.
What I wanted to know is how to pass the parameters using a HTTP POST. It already works with HTTP GET but the username and password are visible from the URL. It would be better to hide them in a POST.
<form method="post" action="home" >
<input name="username" class="form-login" title="Username" value="" size="30" maxlength="2048" />
<input name="password" type="password" class="form-login" title="Password" value="" size="30" maxlength="2048" />
<input type="submit" value="Connect">
</form>
web.xml
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Servlet:
public class HomeController extends HttpServlet {
private HttpSession session;
private UserBean userBean;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
The problem is that the userName and password strings are always empty, meaning that the parameters are never fetched from the POST. What am I doing wrong?
it should work, can you check by changing form method to get and trying, you should see parameters in url.
Please try this
In your doPost(..) method code only doGet(..) and put all your logic in doGet(..) and check if still it is giving blank values.
Let me know what is the output.
Example:-
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
this simple implementation should have worked ..but since its not, there maybe some code which is manipulating the request. The code you have posted is not sufficient to determine that.
Some pointers I can give are -
Check your web.xml to see if there is any filter/interceptor which is manipulating the request.
Which web/app server are you using? Have you checked the service(Http...) method implementation of HttpServlet. You can try placing a debug point in service(..) method to see if the request object here has the required request parameters. If it doesn't, then the problem exists either in some filter or your jsp itself.
What does dispatch(request, response, ApplicationRessource.getInstance().getHomePage()); do? I know the problem is before this line, but this is not a standard HttpServlet method, so I assume there's lot more custom code then whats been posted in the question above.