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.
Related
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 am new in servlets-
I am filling text in form but value in request is null-
In login page-
<body>
<form action="">
<input type="text" name="uname">
<input type="text" name="pwd">
link
</form>
</body>
In DisplayPage-
<body>
Display:
<%
String uname=(String)request.getParameter("uname");
String upass=(String)request.getParameter("pwd");
out.println(uname+" - "+upass);
Enumeration<String> enumeration = request.getParameterNames();
boolean b=enumeration.hasMoreElements();
out.println(b);
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
String data=(String)request.getParameter(name);
out.println(name+" - "+data);
}
%>
</body>
Now in my result value of uname and upass is null and hence boolean b is false.Weird!
My Question Is- If request object is created when we use anchor tag since there is no NPE on calling getParameter() on request object,so what kind of data attached with this request object.why this is provided to us?
Because you are not submitting your form to server or not passing any value in url, instead you are clicking on link, which will redirect it to your link.
<body>
<form action="display.jsp"> // added action
<input type="text" name="uname">
<input type="text" name="pwd">
<button type="submit">Link</button> // added submit button
</form>
</body>
For Updated Question
On server side every request is handled as HttpServletRequest object. So when we submit the form, every input field is submitted and then it is retrieved from the request object on server side.
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 !!
I am working with resteasy with war file deployed on jboss (6.0.2 EAP)
I have the following workflow :
URL hit calls a servlet(doGet() method)
this servlet is supposed to deliver a jsp page to the client
JSP page resides in WebContent/customFolder
I use the requestDispatcher().forward() method to invoke the JSP
The path given in forward("/customFolder/name_of_jsp")
the jsp has a form, whose action attribute points to another servlet
the problem is , once the forward() method is called, the browser returns a 404 resource not found error.
I have followed some questions already posted on this forum and was not able to solve this issue.
Can anyone please guide me.
Edit:
JSP page :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="javax.servlet.*,java.lang.String"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Password Reset Page</title>
</head>
<body>
<form method="GET" action="Resteasy">
<%!String userId;%>
<%userId = (String)getServletContext().getAttribute("userid"); %>
<p>User Id:<%= userId %></p>
Password: <input type="password" name="pwd" id="pass">
<br>
Confirm Password: <input type="password" name="rePwd" id ="c_pass" onblur="confirmPass()"><br>
<script type="text/javascript">
function confirmPass() {
var pass = document.getElementById("pass").value
var confPass = document.getElementById("c_pass").value
if(pass != confPass) {
alert('Wrong confirm password !');
document.getElementById("c_pass").focus();
}
}
</script>
<input type="submit" value="Submit">
</form>
</body>
</html>
The servlet which has to deliver the jsp :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Received request for popup jsp page");
String userId = request.getParameter("userid");
String utc = request.getParameter("utc");
log.info("Recieved userid = "+ userId);
log.info("Received utc is = "+ utc);
ServletContext requestContext = request.getServletContext();
requestContext.setAttribute("userid", userId);
requestContext.setAttribute("UTC", utc);
String htmlfileName = null;
try {
htmlfileName = new DeltaPropertyHandler(
DeltaConstants.LINK_HTML_FILE).getPropertyValue(DeltaConstants
.USER_PASSWORD_RESET_HTML);
File file = new File(requestContext.getRealPath(htmlfileName));
if(file.exists()){log.debug("file exists!!");}
else{log.warn("file does mot exist");}
} catch (Exception e) {
log.error("failed to present the jsp page " + e.getMessage());
}
log.info("File name is "+htmlfileName);
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
rd.forward(request, response);
}
your code:
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
you should change:
RequestDispatcher rd = requestContext.getRequestDispatcher(programname.jsp);
if your using the get method as following as:
RequestDispatcher view=request.getRequestDispatcher(forward);
view.forward(request, response);
if your using the post method like as:
private static String LIST_USER="/listUser.jsp";
RequestDispatcher view=request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
User will be reference from this format. And just look at the simple format are following as:
A.jsp> conntroller.java > dao.java>dbUtil.java
you want the reference for that list as following link to click
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<html>
<head>
<style>
body{
background-color:#F5FFFF;
opacity:0.9;
filter:alpha(opacity=80);
}
h1{
color:#010066;
font-size:80px;
text-align:center;
}
h1.underline{
text-align:center;
margin-top:-20px;
margin-bottom:40px;
}
h2{
color:#010066;
font-size:22px;
text-align:center;
}
h3{
color:#010066;
font-size:14px;
text-align:center;
}
#cen
{
color:#010066;
text-align:center;
}
</style>
<script>
</head>
<body>
</p>
<h1 >ERICSSON</h1>
<h1 class="underline"><img src="line.png" align="top" height="10" width="420"></h1>
<br>
<br>
<h3>Please Enter your Login Details!</h3>
<br>
<br>
<p id='cen'>USERNAME : <input type="text" name="usr"/>
<br>
<br>
PASSWORD : <input type="password" name="pwd" />
<br>
<br>
<input type="button" value="LOGIN" id="LOGIN">
</p>
<%
String Username = request.getParameter("usr");
String Password = request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/proj","root","root");
Statement st = con.createStatement();
ResultSet rs1 = st.executeQuery("select password from login where username = '"+Username+"'");
if (rs1.next())
{
if(rs1.getString(1).equals(Password))
{
}
}
else
{
}
%>enter code here
</body>
</html>
I want to redirect to home.jsp when the user enters correct login details. when the user enters wrong login details then it should stay on the same page and clear the text boxes. i tried a lot of stuff but its not working. please help!
well you can use
<%
String redirectURL = "/Home.jsp";
response.sendRedirect(redirectURL);
%>
but i sincerely suggest using form in your first jsp , submitting the form and then passing it to another JSP
<form action="/Home.jsp">
<!-- keep form elements here -->
<input type="submit">
</form>
as it is a jsp page you can use response.sendRedirect()
note do not use scriplets in jsp page.Better alternate jstl/*el*
If both the form and the jdbc code you have written are in the same page then code part that you are using for checking password will not work because request.getParameter("usr"); and request.getParameter("pwd"); will always give null
You can have muliple options like requestDispatcher and sendRediect
if(rs1.getString(1).equals(Password))
{
response.sendRedirect("URL")
}
And i will recommend you not to have a java code inside jsp