I have a Database with some users in it, which have a username and a password.
I want to make a login form in JSP with 2 fields "login" and "password" if the input from the user is the same as in the database i want it to redirect to homepage.
I know how to do this in php but im completely new to jsp so i have really no idea where to start, i thought javascript would be needed to accomplish this.
I have already seen some comparable questions as mine but no answer seems to really work for me.
Here is my JSP Page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="<c:url value="/resources/css/style.css"/>">
<title>login</title>
</head>
<body>
<div class="login-block">
<h1>Login Page</h1>
<div class="inlog-block">
<form action="" method="post">
<p>Enter Username: </p>
<input type="text" name="username" required="required" /> <br>
<p>Enter password: </p>
<input type="password" name="password" required="required"/><br><br>
<input type="submit" name="loginbutton" value="Login"/>
</form>
</div>
</div>
</body>
</html>
Also i'm already able to get my users from the database in an arraylist in my model so maybe i need to use this in my JSP?
my Employeelist class:
public class EmployeeList {
private ArrayList<Employee> employees = new ArrayList<>();
public EmployeeList()
{
loadEmployees();
}
public void loadEmployees(){
DAOEmployee DAOE = new DAOEmployee();
employees = DAOE.LoadAllEmployees();
}
public ArrayList<Employee> getEmployees() {
return employees;
}
public void setEmployees(ArrayList<Employee> employees) {
this.employees = employees;
}
}
my DAOEmployee class:
public class DAOEmployee extends DAObject{
public ArrayList<Employee> LoadAllEmployees(){
String sql = "SELECT * FROM EMPLOYEE";
Employee e = null;
ArrayList<Employee> employees = new ArrayList<>();
try {
ResultSet rs;
Statement stmt = openConnection().createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
int ide = rs.getInt("id");
String first = rs.getString(2);
String last = rs.getString(3);
String mail = rs.getString(4);
String adres = rs.getString(5);
String zip = rs.getString(6);
String funct = rs.getString(7);
String user = rs.getString(8);
String pass = rs.getString(9);
e = new Employee(ide,first, last, mail, adres, zip, funct, user, pass);
employees.add(e);
}
}
catch (SQLException x) {
// TODO Auto-generated catch block
x.printStackTrace();
}
return employees;
}
}
And my DAObject class:
public class DAObject {
private String url = "jdbc:mysql://127.0.0.1/mydatabase";
private String user = "root";
private String password = "root";
public Connection conn = null;
public DAObject(){
}
public Connection openConnection(){
try{
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesfull");
}
catch(SQLException e){
e.printStackTrace();
}
return conn;
}
public void CloseConnection(){
try{
conn.close();
}
catch(SQLException e){
e.printStackTrace();
System.out.println("");
}
}
}
You need a method to search for a especific user with a differente SQL instruction and you return a object Employee or boolean w/e you want from it:
String sql = "SELECT * FROM EMPLOYEE WHERE USER=? AND PASS=?";
In your servlet you call it and check if there is a registry for this user using the inputs values from your form.
String userName = req.getParameter("username");
Edit:
a)You need a method to search for this user, something like this (DAO layer example):
public User search(String userName, String password, Connection con) throws Exception{
User user = null;
String sql = "SELECT USERNAME, PASSWORD FROM T_USERS WHERE USERNAME=? AND PASSWORD=?";
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, userName);
pStmt.setString(2, password);
ResultSet rS = pStmt.executeQuery();
if(rS.next()){
user = new User(rS.getString("USERNAME"), rS.getString("PASSWORD"));
}
rS.close();
pStmt.close();
return user;
}
b) In you Servlet you check it in doPost method:
String user = req.getParameter("username");
String pass = req.getParameter("password");
Connection con = null;
try {
con = ConexaoFactory.getInst().getConnection("", "");
User user = BOClass.search(user, pass, con);
if(user == null){
//not found;
}else{
//found;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(con != null)
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
This is just a example how you can do it.
Related
I am trying to send login data in JSON format to a servlet using AJAX, but for some reason the servlet is getting null values. My servlet works fine when I send the data without AJAX, but when I use it it seems that my script is not getting any values.
Login form:
<form>
<input class="input-container" type="text" placeholder="Enter Email"
name="email" required><br>
<input class="input-container" type="password" placeholder="Enter Password"
name="paswd" required><br>
<input class="login-button" type="button" value="Log in"
onclick="loginAjax(this.form)">
</form>
AJAX:
function loginAjax(form) {
var user = new Object();
user.email = form.email.value;
user.paswd = form.paswd.value;
var jsonUser = JSON.stringify(user);
console.log(user.email);
console.log(user.paswd);
console.log(jsonUser);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
//Empty form fields
form.email.value = "";
form.paswd.value = "";
}
};
xmlhttp.open("POST", "./login", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonUser);
}
Servlet:
# WebServlet(name = "login", urlPatterns = { "/login" })
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.sendRedirect("index.html");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType(MediaType.APPLICATION_JSON);
response.setCharacterEncoding("UTF-8");
Dao dao = new Dao();
// return values as string.
String email = request.getParameter("email");
String password = request.getParameter("paswd");
System.out.println("Your email: " + email );// Delete Later!!
System.out.println("Your password: " + password);// Delete Later!!
System.out.println("Test passed0");
// Read reference values from DB
String salt = dao.getUserSalt(email);
String hashpw = dao.getUserpasswordHash(email);
System.out.println("Test 1 passed");
dao.checkemail(email);
try {
System.out.println("Test 2 passed");
if (SecurityUtils.isPasswordOk(hashpw, password, salt)) {
System.out.println("Test 3 passed");
String data = email;
HttpSession session = request.getSession();
User user = dao.readUserInfo(data);
dao.close();
System.out.println("Test 4 passed");
session.setAttribute("LoggedUser", user);
System.out.println("Session: " + request.getSession(false));
session.setMaxInactiveInterval(30 * 60);
System.out.println("Test 5 passed");
String encodedURL = response.encodeRedirectURL("/userInfo?email=" + data);
System.out.println("Final Test 6 passed");
try {
response.sendRedirect(encodedURL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
dao.close();
RequestDispatcher rd = getServletContext().getRequestDispatcher("./index.html");
try {
rd.include(request, response);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output I get on the console:
Your email: null
Your password: null
java.lang.NullPointerException
at security.SecurityUtils.getPasswordHashed(SecurityUtils.java:32)
at security.SecurityUtils.isPasswordOk(SecurityUtils.java:57)
at app.Login.doPost(Login.java:54)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:526)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:593)
at org.eclipse.jetty.servlet.ServletHolder$NotAsync.service(ServletHolder.java:1459)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
at org.eclipse.jetty.servlet.ServletHandler$ChainEnd.doFilter(ServletHandler.java:1631)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:148)
at org.eclipse.jetty.servlet.FilterHolder.doFilter(FilterHolder.java:193)
at org.eclipse.jetty.servlet.ServletHandler$Chain.doFilter(ServletHandler.java:1601)
at ..Error continues...
I tried to switch the input type to submit and then added return false next to the onclick as the following onclick="loginAjax(this.form); return false" but that didn't help. I previously used similar ajax function with a form to send data to PHP and it worked fine. Any help would be much appreciated!
From the Documentation of XMLHttpRequest
XMLHttpRequest send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.
Apparently you are sending JSON data into your request body whereas you are expecting your data in request Parameter
String email = request.getParameter("email");
String password = request.getParameter("paswd");
Certainly it will return NULL
In this case you need to read request body from request.getInputStream()
Check this answer
try
xmlhttp.open("POST","./login?email=" + user.email + "&paswd=" + user.paswd,false);
xmlhttp.send();
instead of
xmlhttp.open('POST', './login', false);
xmlhttp.send(jsonUser);
OR YOU CAN USE JQUERY AJAX
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
function loginAjax(form) {
var user = new Object();
user.email = form.email.value;
user.paswd = form.paswd.value;
var jsonUser = JSON.stringify(user);
$.ajax({type: "POST",
url:"./login",
data:jsonUser,
success:function(result){
alert("Success");
}
});
}
</script>
So here is the deal I am working on a simple project, with a log in form and a sign up form. In the beginning you will see this which is displayed in the picture.
After you sign up or log in, then you will get what is displayed in the picture below
When I click on a new page for example: like on the home page, videos, contact, then it will just return back to its original state in the first picture. I want to prevent that and keep it the way it is in the second picture until you click on log out. I have been looking everywhere for answers and can't seem to find exactly what I am looking for.
Here is a little code from what I have used to try and accomplish this
HTML code, which is located in the master page
<a id ="LogIn" runat="server" href="../LogIn.aspx">Log In:</a>
<a id ="SignUp" runat="server" href="../SignUp.aspx">Sign Up:</a>
<a id ="LogOut" href="../LogIn.aspx">Log Out:</a>
CSS code in the master page as well.
#LogIn
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 767px;
}
#SignUp
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 867px;
}
#LogOut
{
margin-top: 30px;
font-size: 20px;
position: absolute;
margin-left: 880px;
display: none;
}
Okay I have tried doing it in javascript, which is in the master page
function showAlert() {
$(".SignUp").slideUp("25000");
$(".LogIn").slideUp("25000");
$(".CreateAccount").hide();
$(".AccountLogIn").hide();
$("h1").remove();
$("#LogIn").remove();
$("#SignUp").remove();
$("#LogOut").show();
}
the showalert function is being called from the button click event in C# for the LogIn form and SignUp form
SqlConnection connection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=**************";
connection.Open();
}
public void CheckEmail()
{
SqlCommand Comm = new SqlCommand("select count(*) from SignUp where Email ='" + Email.Text + "'", connection);
Comm.Parameters.AddWithValue("#Email", Email.Text);
Comm.Connection = connection;
int count = Convert.ToInt32(Comm.ExecuteScalar());
if (count > 0)
{
Thread.Sleep(3000);
VerifyEmail.Visible = true;
}
else
{
Thread.Sleep(5000);
InsertData();
VerifyEmail.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
}
}
public void InsertData()
{
SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(#FirstName, #LastName, #Password, #Email)", connection);
Command.Parameters.AddWithValue("#FirstName", FirstName.Text);
Command.Parameters.AddWithValue("#LastName", LastName.Text);
Command.Parameters.AddWithValue("#Password", Password.Text);
Command.Parameters.AddWithValue("#Email", Email.Text);
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
LogIn.Visible = false;
SignUp.Visible = false;
Command.ExecuteNonQuery();
}
protected void SignUp_Click(object sender, EventArgs e)
{
CheckEmail();
connection.Close();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert()", true);
//Response.Write("<script language=JavaScript> alert('You have Successfully created an Account'); </script>");
//Response.Redirect("~//Default.aspx");
}
I also tried doing it in the back end code as well shown above. It also shows how the user is being loged in and saved in the database. That is being called in the button click event, when you click to create an account or click to log into an account.
LogIn.aspx.cs
SqlConnection conn = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
conn.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=*******";
conn.Open();
}
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
public void ExecuteLogIn()
{
SqlCommand Command = new SqlCommand("select ISNULL(Email, '') As Email, ISNULL(Password, '') As Password from SignUp where Email='" + Email.Text + "'", conn);
SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= #FirstName", conn);
Command2.Parameters.AddWithValue("#FirsName", FirstName.Text);
SqlDataReader dr = Command.ExecuteReader();
string UserEmail = Email.Text;
string UserPassword = Password.Text;
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
while (dr.Read())
{
if (this.CompareStrings(dr["Email"].ToString(), UserEmail) &&
this.CompareStrings(dr["Password"].ToString(), UserPassword))
{
InvalidLogIn.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
//LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
LogIn.Visible = false;
SignUp.Visible = false;
}
else
{
InvalidLogIn.Visible = true;
}
}
//Command.Parameters.AddWithValue("#Password", Password.Text);
//Command.Parameters.AddWithValue("#Email", Email.Text);
conn.Close();
}
protected void LogIn_Click(object sender, EventArgs e)
{
ExecuteLogIn();
}
Any help would be greatly appreciated thanks so much
The code is missing too many pieces. I could only give you a direction. If you have specific question about FormAuthentication, please create a new question.
CheckEmail method is prone to SQL Injection attack. You want to consider using Parameterized Query.
We normally need both username*(or email)* and password to validate an account. Easiest way to implement authentication in ASP.NET Web Form is to use FormAuthentication.
The following is the sample code. I also created a sample project at GitHub, so that you can test it.
Sign-In method inside Login.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
string username = UsernameTextBox.Text,
password = PasswordTextBox.Text;
bool rememberMe = RememberMeCheckBox.Checked;
// Retrieve username and hashed password from database, and validate them
if (username.Equals("johndoe", StringComparison.InvariantCultureIgnoreCase) &&
password.Equals("123456", StringComparison.InvariantCultureIgnoreCase))
{
FormsAuthentication.RedirectFromLoginPage(username, rememberMe);
}
MessageLabel.Text = "Invalid username or password";
}
Global.asax.cs
We then retrieve username from cookie, and save it in Principal Object.
public class Global : HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (decryptedCookie != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
}
web.config
Please ensure authentication tag is in web.config.
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
Usage
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
}
}
I am tring send data to another website's form from my 'Web Form' and submit it. But I couldn't achive it so far. I tried add id's bodyContent_ tag but still no progress. Can you detect where I am doing it wrong ? Thank You
protected void btnSend_Click(object sender, System.EventArgs e)
{
Response.Write(PostForm().ToString());
this.PostScript(Page);
}
public string PostForm()
{
string PostUrl = "http://www.teknobilsoft.com/Contact.aspx";
string Method = "post";
string name = "John";
string email = "john#doe.com";
string subject = "Mesaj";
string message = "some messages";
StringBuilder ppForm = new StringBuilder();
ppForm.AppendFormat("<form id='form1' action='{0}' method='{1}'>", PostUrl, Method);
ppForm.AppendFormat("<input id='txtName' value='{0}'>", name);
ppForm.AppendFormat("<input id='txtEmail' value='{0}'>", email);
ppForm.AppendFormat("<input id='ddlSubject' value='{0}'>", subject);
ppForm.AppendFormat("<textarea id='txtMessage' value='{0}'></textarea>", message);
ppForm.Append("</form>");
return ppForm.ToString();
}
private void PostScript(System.Web.UI.Page Page)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm = document.getElementById('form1');");
strScript.Append("ctlForm.submit();");
strScript.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "btnSendMessage", strScript.ToString());
}
What's the error message do you get?
Also, is there a reason why you use JavaScript to post the data? You can post using HttpWebRequest in C#:
http://www.stickler.de/information/code-snippets/httpwebrequest-post-data.aspx
This is my form in the view..
SendCall is the method in controller to sending email..
#using (Html.BeginForm("SendCall", "Home", FormMethod.Post, new { id = "email-form" }))
{
<label>Name</label>
<input type="text" id="name" value=""/><span class="require"> *</span>
<label>Email:</label>
<input id="Email" type="text" />
<input type="submit" value="Submit" >
}
This is the action code..
[HttpPost]
public ActionResult SendCall(string Date, string Phone, string Name, string Email)
{
string username = "xxxxxx#gmail.com";
string password = "********";
NetworkCredential loginInfo = new NetworkCredential(username, password);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
string message = Name + Email; //I have shortened this line.
try
{
msg.From = new MailAddress("yourname#gmail.com", "My Website");
msg.To.Add(new MailAddress("email#gmail.com"));
msg.Subject = "Contact Message";
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.Send(msg);
return Content("Your message was sent successfully!");
}
catch (Exception)
{
return Content("There was an error... please try again.");
}
}
Can anyone suggest me how to validate this form? By adding some code in ajax code? I want client side validation and not with unobtrusive..
I have added a new SQL Server Database to the App_Data folder from the sample project below.
http://code.msdn.microsoft.com/How-to-consume-JSON-Web-5db0174b#content
I have added 2 new textbox, 1 button in the HTML for user to enter name, address and a click button to save in database.
But I don't know how to pass the value entered from the HTML text box, button using WinJS.xhr to the WCF and then perform CRUD from SQL Server database and will display the output in the app.
default.html
<input id="txtName" type="text" />
<input id="txtAddress" type="text" />
<button id="insertbtn">insert</button>
JSONWCFService.svc.cs
public void Insert(int name, int address)
{
string connectionString = System.Configuration.ConfigurationManager.
ConnectionStrings["Database1ConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "INSERT INTO Table1(Name, Address) VALUES (#Name, #Address)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Address", address);
try
{
con.Open();
int numAff = cmd.ExecuteNonQuery();
}
catch (SqlException exc)
{
}
finally
{
con.Close();
}
}
IAddService.cs
public interface IAddService{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void Insert(string name, string address);}
default.js
function insertButtonClick() {
var baseURI2 = "http://localhost:45573/AddService.svc/Insert";
var name = document.getElementById('txtName').value;
var address = document.getElementById('txtAddress').value;
WinJS.xhr({
type: "POST",
url: baseURI2,
headers: { "Content-type": "application/json" },
data: JSON.stringify(txtName+ txtAddress)
}).then(function complete(request) {
var resdata = request.responseText;
}, function error(er) {
var err = er.statusText;
})
}
Please help to correct my code or share me some correct sample code (WinJS.xhr and JSONWCFService).
Thank you very much!