I am trying to forward my error message back in my login page if user keys in the incorrect password. It works for the first try, but when user retype password regardless of the right or wrong password, it will then return me HTTP Status 404
For an example , in user login JSP .. If user is log in as user,
I will do a condition that it will sendRedirect to user page. where else if user is sign in as Admin , it will sendRedirect to Admin page. ---- This part , it is working perfectly good , i am using dispatcher ----
For an example in the code structure i did
login.jsp
<form action="../loginController" method="post">
<p> Username : <input type="text" id="name" name="username" required/</p>
<p> password : <input type="text" name="password" required/> </p>
<button type="submit"> Submit </button>
</form>
<h2><%=request.getAttribute("errorMessage") %></h2>
/-- It should redirect back to this page when user keys in the wrong password . which in the url should input it as .../login.jsp ---/
/--
I created a servlet file , i call it loginController . My user data i retrieve is from oracle. Everything from fetching of data is perfectly fine
The only problem is when im doing the condition.
---/
Servlet is loginController.java
if(loginRS.equals("user")){
response.sendRedirect("User/User.jsp"); /*--This is working --*/
} else if(loginRS.equals("admin")){
response.sendRedirect("Admin/Admin.jsp"); /*--This is working --*/
} else if(loginRS.equals("IncorrectPassword")) {
/*--- This is where the problem starts ---*/
RequestDispatcher rd =
request.getRequestDispatcher("./Login/login.jsp");
request.setAttribute("errorMessage", "Username Not found");
rd.forward(request, response);
/--Up till here, the code is working , the only problem is that it is storing inside servlet.java rather than to forward it back to login.jsp--/
/-- This is where the problem starts, When i key in the wrong password , it returns errorMessage as username not found. BUT in my urlPath , it states that it is still inside LoginController. if in the second try , i were to input the correct password , it return me 404 page not found --/
I thought of putting this code below to redirect it back to login.jsp if the condition is called. but i am unable to sendreDirect it.
response.sendRedirect("./Login/login.jsp");
}
Thank you in advance
SOLVED
Basically the problem I was facing was my connection , hence its leading to error 404
Try removing ./ or . from request.getRequestDispatcher("./Login/login.jsp");
Related
I'm developing a java based web application, I have also added Login/Logout functionality in my application. For Login, user needs to submit the username and password and that will be passed as a query parameter along with the url. But the problem is, even after logout when the client tries to go back to the loginPage using the back button (left arrow) in browser and reloads the LoginPage url, the url along with query parameters (login credentials) is get submitted again. This enables the user to login again.
How to prevent this and make the user to re-enter the login credentials?
Also from this, I can say that client browser stores the url along with the query parameters.
How to avoid the browser from saving/caching my login credentials?
Thanks in advance! :)
<div class="container">
<form action="Login" method="get">
<h1>Login</h1>
<label>Enter your username </label>
<input type="text" placeholder="username" name="username"/><br /><br />
<label>Enter your password </label>
<input type="text" placeholder="password" name="password"/><br /><br />
<button type="submit" value="Login">Submit</button>
</form>
</div>
QueryString with Login Credentials : http://localhost:8080/DemoApp/Login?username=karthik&password=karthik123
Never send any credentials via URL parameters of a GET request for multiple reasons:
Caching of URLs is always allowed in the browser. If you leave your browser unattended for a moment it may leak your credentials.
All infrastructure elements (firewalls, proxies) along the way are always allowed to log URLs for debug purposes. Credentials may leak because someone turned logging on.
Secrets are allowed to be passed via headers or body of requests. Please use POST request to send the credentials. With a bit of luck this should solve your problem.
I am using tomcat 8 form base authentication security for my application. In web.xml:
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login-failed.html</form-error-page>
</form-login-config>
</login-config>
Is there a way to pass username & password to login.jsp directly through URL POST/GET?
I am trying to connect my application to another application and as such I would like the users to be able to login directly without having to type the credentials again. As such, I am passing the username and credential through a post request to login.jsp from my master application:
<script language="javascript">
<%
String username= (String)request.getParameter("username");
String password= (String)request.getParameter("password");
System.out.println("username========="+((String)username));
System.out.println("password========="+((String)password));
%>
function autologin(){
document.forms[0].j_username.value = "<%=username%>";
document.forms[0].j_password.value = "<%=password%>";
document.forms[0].submit();
}
</script>
<body onload = "javascript:autologin()">
<form method="POST" name="loginform" action="j_security_check">
<table>
<tr>
<td colspan="2">Loading.......</td>
</tr>
<tr>
<td><input type="hidden" name="j_username" /></td>
</tr>
<tr>
<td><input type="hidden" name="j_password"/ ></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" value="Go" /></td>
</tr>
</table>
</form>
</body>
My aim was to pass the credentials like this:
http://localhost:8080/myApp/login.jsp?username=user&password=password
But I am getting the following error:
HTTP Status 400 - Invalid direct reference to form login page
However, the username and password are getting printed correctly meaning they are passed. Apparently, we cannot access the login form directly.
So are there any workaround or if there is some thing incorrect/missing from my code?
Edit 1:
The form.submit() in the javascript works. I tried hard-coding the username & password in the login.jsp page:
<%
String username="user";
String password="password";
%>
And then, directly hitting http://localhost:8080/myApp/ takes me to the application. The only problem is that I cannot access login.jsp page directly from the URL.
As I gather, one simply can't point a browser at the login page because there's no way to tell it where to got next! The login page's action is a builtin process, not a servlet or JSP that could then move you along to the next page.
The idea behind the login facility is that since a user can jump into any part of a webapp that has a distinct URL, thus bypassing a login page, the whole login process is moved external to the webapp so that if someone addresses the webapp and they are not yet logged in, the original URL is intercepted, the login form is presented, and if (and ONLY if) the login succeeds will the original URL be presented.
Hence, we directly cannot pass variables directly or go directly to login.jsp through the URL. The tomcat itself redirects to the login form (mentioned in the web.xml) when the application is accessed if the user is not logged-in.
However, in this case, I found a workaround. Instead of passing the parameters to the login page, passing it to the application directly like this:
http://localhost:8080/myApp/?username=user&password=password
lets us login to the application directly without having to manually type in the credentials in the form. The same can be passed via a POST request from a different application.
In my Liferay 6 app I'm able to pass parameter from java to jsp via:
final PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("view");
request.setAttribute("description", "some description");
rd.include(request, response);
Then I want user to change the description and pass it back to back-end:
<form method="POST" action="${addItem}">
<input name="description"
type="text"
value="${description}"/>
<button type="submit">UPDATE</button>
</form>
Nevertheless when I call then System.out.println("request.getAttribute("description")); , I'm getting null. What am I doing wrong?
Youre passing in the parameter but checking the request attribute (assuming that the outer quotes are a question typo). Based on the information you provided, the initial request attribute was only available in the JSP but not any subsequent servlet. Try
System.out.println(request.getParameter("description"));
I'm facing an issue as to redirecting my website to a certain specific URL...
to better explain, I'm adding an auto refresh meta to the top of my jsp that refreshes the web page every 15 minutes, the only problem here is that when the 15 minutes are over, instead of refreshing the same page (thus calling the same servlet to recalculate what needs to be recalculated) it redirects to the home page!(defined in xml as login.jsp)
Now I've tried to debug the code to see which part is redirecting to the home page but it seems that it's no power of my own! it's probably something Tomcat is doing that I'm not aware of. It already happened to me before and the solution was to add an attribute to the session scope session.setAttribute("User",user);
but not this time...
To support my point(It's not a session problem), here's a portion of the code directly extracted from the page source code after redirection
<header>
<h1>WelcomeTV</h1>
</header>
<section>
<form action="Login" method="post">
<ul>
<li><label for="username">Username</label></li>
<li><input type="text" name="user" id="username" placeholder="Your Username" value="wtv_administratifs"></li>
<li><label for="password">Password</label></li>
<li><input type="password" name="password" id="password" placeholder="Your Password"></li>
<li><input type="submit" value="Log in"></li>
</ul>
<p class="reset_pwd">Reset your password</p>
<p class="change_pwd">Change your password</p>
</form>
</section>
You can see that the value is filled, and in my jsp the value is taking ${sessionScope.username} so this proves that the session is still valid
Please help me? if it's not clear please let me know, I'll try to make myself clearer.
Set up your session config in your web xml to -1 if you do not want it to expire
Well, This is embarrassing... It seems the little problem I have has nothing to do with the previous one I resolved with an input into the session scope.
The issue was simply that the URL after logging into my website stays //Context/Login (HTTP POST ><) and with the meta auto refresh, it does not refresh the servlet called after the login, it actually refreshes the same URL displayed above => Login and thus redirects me to the login page...
Issue resolved by adding
<META HTTP-EQUIV="refresh" CONTENT="900;URL=http://10.84.18.53:8080/Welcome_TV/display"> which is the servlet that needs to do all the recalculation.
Issue resolved, thank you for you comments and terribly sorry for your time :)
Since this not really answers my question, I'm gonna clarify.
3 .jsp pages, index.jsp, calculator.jsp and error.jsp.
index.jsp contains (withoug html and body tags):
<p><b>Enter the Number you want to know the square root of:</b></p>
<form action="calculator.jsp" method="post">
<div><input type="text" name="number_textfield" size="40" /> <input type="submit" value="Send" /></div>
</form>
error.jsp contains (without html body tags):
<%#page isErrorPage="true" import="java.io.*" %>
<%
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
String exceptionstack = sw.toString();
%>
<p>Path to File causing this error:
<span class="errortext"><%= request.getAttribute("javax.servlet.error.request_uri") %></span><br />
Error Message: <span class="errortext"><%= exception %></span><br />
The Error is: <span class="errortext"><%= exception.getMessage() %></span><br /></p>
<hr />
<p>Exception stack:</p>
<pre class="errortext"><%= exceptionstack %></pre>
<p>Index Page</p>
Now in calculator.jsp....
1) If I leave the textfield empty in index.jsp, I'm gettin displayed the error according to error.jsp.
2) If I enter a number smaller than 0, nothing happens. Now I've tried various methods from there. None of them works.
The calculator.jsp (without body and html tag):
<%# page errorPage="../WEB-INF/sqrterror.jsp" %>
<%
String number_string = request.getParameter("number_textfield");
double number = Double.parseDouble(number_string);
if (number < 0){
//THAT'S WHAT I'M MISSING HERE :(
%>
<%
}
else{
double sqrt = Math.sqrt(number);
%>
<p>Square Root of <%= number %> is <%= sqrt %> .</p>
<p>Back to Index Page</p>
<%
}
%>
You've one big problem here: if you throw an Exception halfway a JSP file, then the chance is big that it will never reach the error.jsp, simply because the response is already committed. The response headers are already set, the response writer is already obtained, the response content is already sent to the client (even if only partly), all only because of the fact that the JSP does that by nature as being a pure view technology. This is a point of no return. The enduser may end up with a blank page and you may end up with an IllegalStateException in the server logs.
If you are very, very lucky, everything is still in the buffer which is not flushed yet, then the webcontainer can still manage to reset it all and forward the request to error.jsp. But I wouldn't rely on that. Writing raw Java code in JSP files is considered bad practice.
Better use a Servlet class. I'll give you a kickoff example. Change your index.jsp as follows:
<h4>Enter the Number you want to know the square root of:</h4>
<form action="calculator" method="post">
<input type="text" name="number" size="40" />
<input type="submit" value="Send" />
${error}
</form>
The ${error} should display the error message, if any. The servlet can set it as a request attribute.
Change your result.jsp as follows:
<p>Square Root of ${param.number} is ${result}.</p>
The ${param.number} should display the "number" request parameter. The ${result} should display the result, if any. The servlet can set it as a request attribute.
Create a Servlet class CalculatorServlet:
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String number = request.getParameter("number");
// Check if number is set and if it is valid, with little help of regex.
// Those are valid: "12" and "12.34", but those not: "-1" or "" or null.
if (number != null && number.matches("^\\d+(\\.\\d+)?$")) {
request.setAttribute("result", Math.sqrt(Double.parseDouble(number)));
request.getRequestDispatcher("result.jsp").forward(request, response);
} else {
request.setAttribute("error", "Please enter valid number.");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
Note that I don't throw exceptions, but just validate the values and set an user-friendly error message for the case that the input is wrong. You should expect that the user can enter wrong values. Never trust user input, always validate it in a proper manner. Your application should not look like to "drastically break" on wrong user input. Exceptions are only affordable if for example the backend DB is down and more of those kind of unrecoverable matters.
Now map this servlet in web.xml as follows (oh, ensure that you're using Servlet 2.4 or newer to get EL (Expression Language, the ${} things) to work in template text):
<servlet>
<servlet-name>calculator</servlet-name>
<servlet-class>com.example.CalculatorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>calculator</servlet-name>
<url-pattern>/calculator</url-pattern>
</servlet-mapping>
The url-pattern should cover the action url as you're going to use in the <form action>.
That should be it. Much nicer separation of business logic and the presentation logic. That's a good start of the MVC way.
Just add
throw new IllegalArgumentException("Number must be non-negative");