request param not set in jsp request dispatcher - java

I'm doing a request forward to another JSP from a JSP with some params in the request object.
JSP1
session.invalidate();
request.setAttribute("errorMessage", "Invalid user or password");
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/userlogin.jsp");
requestDispatcher.forward(request, response);;
userlogin.jsp
<%
if(null!=request.getAttribute("errorMessage"))
{ %>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span> <%=request.getAttribute("errorMessage")%> </span>
</div>
<% }
else{
System.out.println("no request");
}
%>
Now Im not able to get the request parms from the request. Its always null in userlogin.jsp.
any help?

Can you try without the statement
session.invalidate();

Move session.invalidate() in userLogin.jsp because If you invalidate the session your parameter are not retrieve.

Related

Passing current username in location.href in jsp page

Is it possible to do? I want to pass a user to a servlet:
#WebServlet("/profile")
so that the URL would be like this: /profile?username=currentusername
I tried:
<%
HttpSession session1 = request.getSession(false);
String username = (String) session1.getAttribute("username");
%>
<div class="navbar-item"
onclick="location.href =
'${pageContext.request.contextPath}/profile?username=${requestScope.username}'
My profile
</div>
But it doesn't work.

JSP doesn't pass values on request

I'don't understand why servlet doesn't pass values to .jsp file. If somebody could explain my, why it works only when a call request.getSession.setAtribute() method. What should i do to avoid creating session.
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
moviesList(request, response);
if (request.getParameter("command").equals("ADD"))
addMovie(request, response);
if (request.getParameter("command").equals("DELETE"))
deleteMovie(request, response);
if (request.getParameter("command").equals("SEARCH_IN_TMDB"))
searchInTmdb(request, response);
} catch (Exception e) {
e.getMessage();
}
}
private void searchInTmdb(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<MovieDb> movieDbs;
String title = request.getParameter("title_themoviedb");
String year = request.getParameter("year_themoviedb");
System.out.println("title " + title + " year " + year);
int year_int = Integer.parseInt(year);
movieDbs = TheMovieDbApiUtil.getInstance().getListFoundMovies(title, year_int);
request.getSession().setAttribute("TMDB_LIST", movieDbs);
RequestDispatcher dispatcher = request.getRequestDispatcher("/movie-list.jsp");
dispatcher.forward(request, response);
}
JSP file:
<div class="row top-buffer">
<form action="ServletMovieController" method="get">
<input type="hidden" name="command" value="SEARCH_IN_TMDB">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<button type="submit">Szukaj...</button>
<input type="text" name="title_themoviedb" title="title_themoviedb" class="form-control">
<input type="text" name="year_themoviedb" title="year_themoviedb" class="form-control">
<ul class="list-group" id="myList">
<c:forEach var="tempMovieTmdb" items="${TMDB_LIST}">
<li class="list-group-item">${tempMovieTmdb.getTitle()}</li>
</c:forEach>
</ul>
</input>
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
</form>
</div>
As I mentioned before it works when I use requset.getSession(), but whitout it passed value is null.
I think i've understood what is going wrong and it's a common mistake people make when they first start out with the servlet/jsp request flow.
As someone has already mentioned you need to swap out
request.getSession().setAttribute("TMDB_LIST", movieDbs);
with:
request.setAttribute("TMDB_LIST", movieDbs);
Now the reason why you're getting null, is because you're not running the servlet. You're trying to access the jsp directly and expecting the request variable to be there. That's not how servlet/jsp request flow works. The servlet sets the request variable "TMDB_LIST" and it forwards this variable to the jsp page ("/movie-list.jsp"). Once you go to a different page the variable expires and will be null. If you try and access the jsp directly, it will just be null because you need the servlet to pass the variable to the jsp. I'm guessing this is what you're doing or you have a redirect after reaching the jsp.
Session variables are different in that the variables you set persist across the whole application/website (until you delete them or change them), for as long as the server specifies.
Request variables are only available after the first request. (i.e. servlet passes request variables to the jsp or the jsp passes request variables to the servlet)
if you want to avoid using Session, in your servlet, use
request.setAttribute("TMDB_LIST", movieDbs);

How to Display incorrect password error in html page without using javascript

I want to display the Password wrong error in html page , i can do it in different page by using requestdispatcher but how to display it in same login page using only java and html , i dont have any idea about javascript , thank you
HTML Code :
<p>Sign into your account</p>
<form action="bs" align="center" method="POST" onSubmit="return
validateLogin()">
<input type="text" name="u_name" placeholder="Username"><br>
<input type="password" name="pswd2" placeholder="Password"><br>
<br>
<input type="submit" value="Login!" >
<span style="color:red;">${errMsg)</span>
</form>
Servlet Code :
if(rs.next())
{
ResultSet rs1=stmt.executeQuery(vsql1);
if(rs1.next())
{
out.println("----Welcome----");
}
else
{
request.setAttribute("errMsg", "Invalid username or password");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
dispatcher.forward( request, response);
}
}
else
{
request.setAttribute("errMsg", "Invalid username or password");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
dispatcher.forward( request, response);
}
}
PrintWriter out=new PrintWriter();
out.println("Password mismatch);
It will display this value in browser

How can I send my requestdispatcher to two different jsp pages path?

I have made a registration form with the use of JSP, beans and JDBC (MVC)
In my servlet, I have the following code..
if ("editRegister".equalsIgnoreCase(action)) {
StudentBean user = new StudentBean();
user.setName(Name);
user.setStudID(ID);
user.setCourse(Course);
user.setEmail(Email);
db.addRecord(Name, ID, Name, Email);
set the result into the attribute
request.setAttribute("StudentBean", user);
RequestDispatcher rd;
rd = getServletContext().getRequestDispatcher("/DisplayRegistry.jsp");
rd = getServletContext().getRequestDispatcher("/UpdateRegistry.jsp");
rd.forward(request, response);
Basically, i want to send my requestDispatcher to two jsp pages so that I can display another form with predefined values inside the form.
e.g.
<jsp:useBean id="StudentBean" scope="request" class="ict.bean.StudentBean"/>
<% String email = StudentBean.getEmail() != null ? StudentBean.getEmail() : ""; %>
<form method="get" action="updateregistry">
<input type="text" name="email" maxlength="10" size="15" value="<%=email%>">
</form>
However, the problem is it displays null instead of the value as the requestDispatcher is only sent to one path.
Your practice of having two forwards makes no sense
rd = getServletContext().getRequestDispatcher("/DisplayRegistry.jsp");
rd = getServletContext().getRequestDispatcher("/UpdateRegistry.jsp")
Instead you can set the value to the session , so that you can access it in both the pages (throughout the application session).
so ,
HttpSession session=request.getSession(false);
session.setAttribute("StudentBean", user);
You can get the values from the session and have a single request dispatcher
Hope this helps !!

How to show alert in a jsp from a servlet and then redirect to another jsp?

I tried this but does not display the message only redirects
login.jsp
<form method="post" action="Login_Servlet" >
<input name="idUsuario" type="text"/>
<input name="password" type="password" />
<button type="submit">Entrar</button>
</form>
Login_Servlet
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userid= request.getParameter("idUser");
String password = request.getParameter("password");
Login_Service login_Service = new Login_Service();
boolean result = login_Servicio.aut(userid, password);
Usuario user = login_Servicio.getUsuariosByUsuario(userid);
if(result == true){
request.getSession().setAttribute("user", user);
response.sendRedirect("vistas/Inicio.jsp");
}
else{
out.println("<script type=\"text/javascript\">");
out.println("alert('User or password incorrect');");
out.println("</script>");
response.sendRedirect("index.jsp");
}
Is it possible to display a message like this? if so I'm doing wrong?
You may possibly do this:
else
{
out.println("<script type=\"text/javascript\">");
out.println("alert('User or password incorrect');");
out.println("location='index.jsp';");
out.println("</script>");
}
Edited: 20th March 2018, 08:19 IST
OR without using js
else {
out.println("<meta http-equiv='refresh' content='3;URL=index.jsp'>");//redirects after 3 seconds
out.println("<p style='color:red;'>User or password incorrect!</p>");
}
You could redirect to your jsp but pass a message to be displayed:
request.setAttribute("loginError","Incorrect password");
Then in the jsp:
<c:if test="${not empty loginError}">
<script>
window.addEventListener("load",function(){
alert("${loginError}");
}
</script>
</c:if>
The not empty syntax allows checking for the existence of a parameter
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<script type=\"text/javascript\">");
pw.println("alert('Invalid Username or Password');");
pw.println("</script>");
RequestDispatcher rd=request.getRequestDispatcher("userlogin.jsp");
rd.include(request, response);
From Servlet, redirect to another jsp normally as you do, and on jsp "onload" event call a javascript function which will give you the alert you need.....

Categories