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 !!
Related
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.
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.
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.....
How can I redirect a response of a servlet to the same jsp page from where I get the request. Suppose I have a tab called status on my jsp page
http://localhost:8080/Example/status.jsp. Now when I send a request and when I get a response,it should display the response on the same page, ie. it should show response on
http://localhost:8080/Example/status.jsp. But it is showing me the response in
http://localhost:8080/Example/Statuswhere Status is the url-pattern in web.xml file. Please any help is appreciated. below is my code.
How do I get the response in status.jsp.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
try{
String showstatus =req.getParameter("showstatus");
PrintWriter out = res.getWriter();
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\tools\\server\\util stat -a" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
BufferedReader input = new BufferedReader(stdInput);
String stat = "";
while((stat = input.readLine()) != null){
out.println(stat);
}
}
catch (Throwable t)
{
t.printStackTrace();
}
finally {
} }
JSP CODE:
<div id= "status" style="display:none;">
<FORM action="status" METHOD="POST">
<input type=submit name=showstatus
id=txtSubmit value=Status />
</FORM>
</div>
WEB.XML:
<servlet>
<servlet-name>Status</servlet-name>
<servlet-class>com.emc.clp.license.Status</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Status</servlet-name>
<url-pattern>/status</url-pattern>
</servlet-mapping>
In your servlet, rather than printing the output of util directly to the response, hold it in memory and pass it to the jsp:
String stat;
StringBuffer utilOutput = new StringBuffer();
while((stat = input.readLine()) != null){
utilOutput.append(stat + "\n");
}
req.setAttribute("utilOutput", utilOutput.toString());
req.getRequestDispatcher("/Example/status.jsp").forward(req, res);
In your jsp, I assume you have a div or something where you want to see the output:
<div id= "status" style="display:none;">
<form action="/status" method="POST">
<input type="submit" name="showstatus" id="txtSubmit" value="Status" />
</form>
</div>
<div id="result">
<pre>
${requestScope.utilOutput}
</pre>
</div>
Notice that I added a forward slash in the form action. If your user is submitting the form from /Example/status.jsp, then the relative path would have the post going to /Example/status, but your servlet only handles requests to /status.
Your request object, req, has a map of attributes, and you can put any relevant objects in it using the setAttribute() method on the request. The request dispatcher forwards your request and response objects on to another resource (your jsp) for processing. The jsp can access these values by name, using the EL notation above.
The display:none in your inline style will always prevent that form from being seen on the page if it loads that way. I think the most apparent way to display it would be with javascript on the client side. You'd need to change the display value when the tab is clicked. You don't mention what your tab elements are, but let's say they're divs. You could write a javascript function to load the form, or you could even do it all inline:
<div id="mytab" onclick="document.getElementById('status').style.display = 'block';">Load the form</div>
I am creating a login page for my web application. I want to create a session object whenever
a new user logged in. I know the concept of sessions, but i didnt used that before. Can i do it with a simple class. Or, i have to move to servlet.
If i shall do it with a simple class means, how to create a session object.
This is my scenario...
The HTML CODE:
<table>
<tr>
<td>User Name: </td><td><input id="uName" class="required" type="text"
size="5" /></td>
</tr>
<tr>
<td>Password: </td><td><input id="pwd" class="required" type="text" size="5"
onclick="login()"/></td>
</tr>
</table>
The JS Code:
function login(){
var userDetails = { uName : null, pwd : null };
dwr.util.getValues(userDetails);//Yes, i am using DWR.
LoginAuthentication.doLogin(userDetails, loginResult);
}
function loginResult(nextPage){
window.location.href = nextPage;
}
The Java Code:
public class LoginAuthentication
{
public String doLogin(User user) throws SQLException, ClassNotFoundException{
String userName = user.getUserName();
boolean loginResult = verifyUser(user);//Another method that verifies user details with the DB.
if (loginResult == true){
/* Here I have to create session object,
and i want to add the current username in that object. How to do it.*/
return "MainPage.html";
}
else{
return "loginRetryPage.html";
}
}
The concept that was given to me about session is pretty simple and clear. I have to create a session object after a valid user input & add the user name to that object, Destroy the object when logout was clicked. But i didnt worked on sessions before. I mean, i dont know the syntax to create a session variable.
How shall i create a session Object here?
Any suggestions would be more appreciative!!!
Thanks in Advance!!!
In a servlet a session is obtained with the following line:
Session session = request.getSession();
And to get the request object with DWR, you do (see here):
WebContext ctx = WebContextFactory.get();
HttpServletRequest request = ctx.getHttpServletRequest();
(The HttpServletRequest contains all data about the HTTP request that has been sent by the browser to the server)
It is better to always use request.getSession(false); after successful login.