Im fairly new to programming in JSP and I am making this web application where users need to log-in. I've done the registration of users but I am having problems when users are logging-in.
The main problem I am having is that, even though a user is able to successfully log-in, the information from the login form is lost. I need to retain the login information so that I can access the user's information during his/her session using the web application.
Here is the code that I currently have:
index.jsp (this is where the login form is shown)
<form name="Login Form" action="login.jsp"><table>
<tbody>
<tr>
<td><input type="text" name="emaillogin" value="email"/></td>
<td><input type="text" name="passlogin" value="password"/></td>
</tr>
<tr>
<td colspan="2" align="RIGHT><input type="submit" value="login" name="Login"/></td>
</tr>
</tbody></table></form>
login.jsp (this performs checking whether the user is valid or not, and redirects it to the user homepage if valid)
<%!
String email = "";
String password = "";
%>
<%
List users = new ArrayList();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "pass");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT email,password FROM users");
while (result.next()) {
users.add(result.getString(1));
users.add(result.getString(2));
}
con.close();
email = request.getParameter("emaillogin");
password = request.getParameter("passlogin");
int hasUser = 0;
Iterator<String> it = users.iterator();
while (hasUser == 0 && it.hasNext()) {
if (email.equals(it.next()) && password.equals(it.next())) {
hasUser = 1;
}
}
if (hasUser == 1) {
response.sendRedirect("homepage.jsp");
} else {
response.sendRedirect("index.jsp");
}
%>
homepage.jsp (this is where the user is redirected to after logging in, showing his/her email address)
.
.
<% out.println("Logged in as: " + request.getParameter("email")); %>
.
.
The current problem is that, null value is what I am getting from homepage.jsp. How can I solve this problem?
Thank you!
First of all I'll say - Avoid Java code in Jsp. Don't use JSP and Scriptlets to perform database operations. Always use Servlets.
You can use Jsp implicit tags (actions), EL and JSTL tag lib to format or present the data.
As per your question, you have to use session object to store data in one page and use them on another page.
I agree with putting this code into a servlet. A quick and simple way to pass a parameter is to the following:
response.sendRedirect("homepage.jsp?email="+email);
First of all let me give a clarity on Request parameters. Usually, request parameters will be in scope of request. So when you ask them in "Login.jsp" it will give you the email, password and what ever the fields you supplied from form. But when you are sending redirect to home page, those parameters won't be carried. So, when you find the user name and password is correct/ valid place them in session. So that you don't have to pass parameters manually to any request. Instead you can directly take the user name from "session" object and display where ever you want. This would be there in session, till the end of that session.
int hasUser = 0;
Iterator<String> it = users.iterator();
while (hasUser == 0 && it.hasNext()) {
if (email.equals(it.next()) && password.equals(it.next())) {
hasUser = 1;
}
}
if (hasUser == 1) {
session.setAttribute("email", email);
response.sendRedirect("homepage.jsp");
} else {
response.sendRedirect("index.jsp");
}
Usually this would be the process in real time. Of course Java code is not recommended here to use. Use JSTl, EL tags instead. In homepage.jsp you can display the email by taking from session.
Of course its too late reply.I guess this might help somebody facing the same problem.
Related
I'm working in Yii2 with the Adldap extension found here: https://github.com/Adldap2/Adldap2
I'm running into an issue when I try to authenticate users on my ldap server. I can successfully make a connection and and retrieve user data, but when trying to authenticate if a user's username and password are correct or not, it always returns true, even if the creds are wrong. Below is my code snippet (with the config array not showing of course):
$ad->addProvider($config);
try {
// If a successful connection is made to your server, the provider will be returned.
$provider = $ad->connect();
//User below does return the correct information from the ldap server
$user = $provider->search()->users()->find('quillin');
try{
$provider->auth()->attempt("wrongUsername","wrongPassword");
die("WIN");
}catch( Exception $e ){
die("Exception " . $e);
}
}catch (\Adldap\Auth\BindException $e) {
die( "There was an issue binding / connecting to the server. <br />" . $e);
}
No matter what I put in for the username and password fields, it always returns true and hits the die("WIN"); line. In my composer.json file, i'm using "adldap2/adldap2": "v7.0.*"
I have also tried to bind the user using the following:
try{
$provider->auth()->attempt("wrongUsername","wrongPassword", $bindAsUser = true);
die("WIN");
}catch( Exception $e ){
die("lose :(");
die("Exception " . $e);
}
And that also always returns true;
I figured this out and will explain here in anyone else has the same issue.
1) $provider->auth()->attempt() should be wrapped in an IF, and not a try/catch.
2) The first parameter, $username, is actually looking for the userprincipalname, the docs had made it sound like it was looking instead for a username.
After that, I was able to authenticate the user successfully.
Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .
I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!
The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};
For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!
I am trying to Login with username and password in this way.Based on input values the pages should redirect.But i am not able to login.
<%#include file="database.jsp" %>
<%
String User = request.getParameter("User");
String Pass = request.getParameter("Pass");
if (User.equals("admin") && Pass.equals("admin123")) {
response.sendRedirect("AdminHome.jsp");
} else {
response.sendRedirect("Adminerror.jsp");
}
if (User != "admin") {
String sql = "select * from user where username='" + User + "' and password='" + Pass + "'";
rs = st.executeQuery(sql);
if (rs.next()) {
response.sendRedirect("userhome.jsp");
} else {
response.sendRedirect("usererror.jsp");
}
}
%>
You are using scriplet when you should use servlets. Servlets are simpler to write, test and debug than scriplets.
In you code, you will never properly reach the user part. Either you give correct admin user and pass and you should be redirected to AdminHome.jsp, else you pass through the response.sendRedirect("Adminerror.jsp");
If user was admin you should be properly redirected to AdminHome.jsp (provided there is nothing else after what you show). But else you will call twice sendRedirect which should cause an error.
You should at least test separately user and password for the admin part to avoid the response.sendRedirect("Adminerror.jsp"); branch if user is not admin and the multiple redirection error.
You should also try to type directly in your browser the URL with AdminHome.jsp to be sure that it is correctly accessible from the browser.
I'm working on a ASP.NET MVC3 application and I've created a database in MySQL 5.5 which contains a company table having a one-to-many relationship with a contacts table.
table Bedrijf (with navigation property "contacts")
table Contact
Since I had to take over this database from a currently running site I generated a Entity Model based on that database and I wrote the following code to display a list of companies (grouped by status), mentioning the number of contacts in that company:
CompanyRepository.cs
...
public IQueryable<Bedrijf> getCompaniesByStatus(int status)
{
return entities.Bedrijven.Where(c => c.bedrijf_status == status).OrderBy(c => c.bedrijf_naam);
}
...
View calling 3 partial Views
#{Html.RenderPartial("ucCompaniesByStatus", Model.newCompanies, (new ViewDataDictionary { { "Titel", "Nieuwe bedrijven" } }));}
<br />
#{Html.RenderPartial("ucCompaniesByStatus", Model.activeCompanies, (new ViewDataDictionary { { "Titel", "Actieve bedrijven" } }));}
<br />
#{Html.RenderPartial("ucCompaniesByStatus", Model.inActiveCompanies, (new ViewDataDictionary { { "Titel", "Niet actieve bedrijven" } }));}
Partial View
#model IEnumerable<xxx.Models.Bedrijf>
<table id="companytable">
<tr>
<th id="thtitle">
#ViewData["Titel"]
</th>
<th id="thactions"></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(#item.bedrijf_naam, "CompanyDetails", new { id = item.bedrijf_id })
(#item.contacts.Count contact(en))
</td>
<td id="actions">
#Html.ActionLink("Edit", "CompanyEdit", new { id=item.bedrijf_id }) |
#Html.ActionLink("Details", "CompanyDetails", new { id = item.bedrijf_id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.bedrijf_id })
</td>
</tr>
}
</table>
In my list of companies, I would like to display the number of contacts assigned to that company but I got the following Error:
There is already an open DataReader associated with this Connection which must be closed first.
When go to my .edmx file and set Lazy Loading Enabled : False I'm able to get a result (But the count on my contacts is not working (I get 0), assuming my related contacts are not loaded now.):
How Can I get this working with Lazy Loading Enabled? My beginner ASP.NET (MVC) skills don't bring me to a solution at the moment.
Adding MultipleActiveResultSets=True; in the web.config connectionstring is pointed out as solution often, but no difference in my case.
Tried the .Include in my CompanyRespository while having lazy loading set to False, but I think I didn't do that correctly since I'm not familiar witht he syntax.
This description makes also sense;
It is not about closing connection. EF
manages connection correctly. My
understanding of this problem is that
there are multiple data retrieval
commands executed on single connection
(or single command with multiple
selects) while next DataReader is
executed before first one has
completed the reading. The only way to
avoid the exception is to allow
multiple nested DataReaders = turn on
MultipleActiveResultSets. Another
scenario when this always happens is
when you iterate through result of the
query (IQueryable) and you will
trigger lazy loading for loaded entity
inside the iteration.
but no idea how I should fix this problem in my code with this information. Where/How use #item.contacts.Count to show the number of contacts?
Thanks in advance.
I had similar Issue. Noticed that was using IEnumerable collection and was calling another function, where was querying database. Since it was IEnumerable collection, reader was open. Changed IEnumerable to list to resolve the issue.
Try using this:
public IQueryable<Bedrijf> getCompaniesByStatus(int status)
{
return entities.Bedrijven
.Include("contacts")
.Where(c => c.bedrijf_status == status)
.OrderBy(c => c.bedrijf_naam);
}
I think MySql connector probably doesn't support multiple active result sets and because of that the setting in connection string didn't help you.
The MySQL connector does not support MultipleActiveResultSets, so that connection string modification will not work.
To get around the issue, in your controller, simply add the .ToList() method to wherever your data is queried..
For example...
public ActionResult Create()
{
ViewBag.PossibleCompanies = context.Companies.ToList();
return View();
}