Get method when page loading in jsp - java

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')%>">

Related

Java Servlet response doesn't seem to finish

First of all, please have mercy for this noobie question. I’m currently working on a web application project and stumbled across this basic problem I can’t figure out to fix.
Basically, I have the following:
index.html sending a POST request to servlet1.
servlet1 sending a redirect to the browser to servlet2.
servlet2 to return content.
I do see the content returned from servlet2 in my browser, but when I look into IE Developer Tools (F12), I see that the GET request to servlet2 never finishes (STATUS PENDING). There must be something very basic that I’m missing…
In below screen shot, "Ausstehend" translates to "pending".
IE Screenshot:
index.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="servlet1" method="post">
<input type="text" name="test" placeholder="some data">
<button type="submit"><b>send</b></button>
</form>
</body>
</html>
servlet1:
public class servlet1 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("servlet2");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
servlet2:
public class servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet2</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>HELLO</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

servlet url pattern with parameters issue

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 />

Passing parameter from JSTL to servlet through <a href> and jstl tags

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>

request.getParameter("Submit") always get null

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");

Java EE: Getting parameters from POST for a login form

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.

Categories