JSON and java servlet - java

I have a html login page, where the user has to put in a number and if this number is registered in the database the user is redirected to a certain site. If the number is not in the database the user get's to see an error message. At the moment I am doing this with a java servlet a local mySql database and tomcat 8.0 and it works perfectly. But I need to use a remote database by accessing it with JSON, I filled the database with a poster addon on mozilla firefox and I can see what is in the database. So it needs to check the user input on the HTML page with the data in the database via json and grant access or not. This is my java servlet that connects to my mysql database.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class servlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String Ticketnumber = request.getParameter("Ticketnumber");
if(Ticketnumber.length() >= 16 || Ticketnumber.length() <= 14){
response.sendRedirect("http://localhost:8080/Error.html");
}
String DB_URL="jdbc:mysql://localhost/ticketnumbers";
String USER = "root";
String PASS = "password";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
final String sql;
sql = "select Ticketnumber from users where Ticketnumber='"+ Ticketnumber +"' limit 1";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if(rs != null && rs.next()){
response.sendRedirect("http://localhost:8080/Welcome.html");
}else{
response.sendRedirect("http://localhost:8080/Error.html");
}
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

I think with "a remote database by accessing it with JSON" you mean a remote Web Service.
You will first need to download the JSON data by making a Java HTTP request and then parsing the retrieved string as JSON using a parser library (GSON is very good for this).
After that, you can do your logic and validate the Ticketnumber against the parsed JSON object.
You will not need to connect to any database since you will get the data via HTTP, the same way you get them via Poster in Firefox. Poster does not know what database (if any) is being used by the remote site, it only needs the URL.

Related

user verification email and password (Java web,servlets)

I've created a simple login web where the user enters the email and password and checks if the user and password are correct then he gets redirected to a welcome.jsp page , where it says login success , I'm checking 3 emails and passwords and creating session for each one , the problem I'm facing is that if the user enters the email or password wrong after 3 attempts he will be blocked for a certain amount of time and after the time expires he can try again , I can't think of a way of doing this , is there a way in which this could be done ?
import java.io.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
//#WebServlet(name = "loginController", value = "/login")
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
String er = "Invalid user info";
int attempts = 3;
PrintWriter printWriter = response.getWriter();
LoginBean loginBean = new LoginBean();
loginBean.setEmail(email);
loginBean.setPassword(password);
try
{
if(email.equals("Mhamdoon4#gmail.com") && password.equals("pass001"))
{
System.out.println("Admin's Home");
HttpSession session = request.getSession(); //Creating a session
session.setAttribute("Mohammed", email); //setting session attribute
request.setAttribute("email", email);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}
else{
attempts--;
printWriter.println(attempts + " left");
}
if(email.equals("Mhamdoon6#gmail.com") && password.equals("pass0011"))
{
System.out.println("Editor's Home");
HttpSession session = request.getSession();
session.setAttribute("Ali", email);
request.setAttribute("email", email);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}
else{
attempts--;
printWriter.println(attempts + " left");
}
if(email.equals("Mhamdoon12#gmail.com") && password.equals("pass00901"))
{
System.out.println("User's Home");
HttpSession session = request.getSession();
session.setAttribute("Adam", email);
request.setAttribute("email", email);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}
else{
attempts--;
printWriter.println(attempts + " left");
}
// if()
// {
// System.out.println("Error message = Invalid info");
// request.setAttribute("errMessage", er);
//
// request.getRequestDispatcher("fail.jsp").forward(request, response);
// }
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
public void destroy() {
}
}
The easiest way, as your example is simple (string literals checking), is keeping the attempts in the session. This way the attempts are tied up to the session (in other words, to the browser's cookies).
To set the values in the session:
request.getSession().setAttribute("loginAttempts", 3);
request.getSession().setAttribute("lastLoginAttempt", LocalDateTime.now());
To read them:
Integer attempts = (Integer) request.getSession().getAttribute("loginAttempts");
LocalDateTime lastLoginAttempt = (LocalDateTime) request.getSession().getAttribute("lastLoginAttempt");
Now you just have to play with the values, recalculate, and reset them after a successful login. The variables will be kept as long as the browser session is kept.
TL;DR;
I see that everyone who ends up here may need a bit of a briefing about requests and sessions.
You have to understand that the piece of code that goes inside de doGet or doPost is executed every time you enter the url in the browser (The int attempts = 3; from your original post is executed every time, so it will always be 3).
The server collects all the data that comes from the client's browser request and builds a brand new HttpServletRequest object that contains all the data (url, request params, cookies, ip, port, etc.) every time. Press f5? everything gets executed again with a brand new HttpServletRequest.
The way the servers use to keep a conversational state between the server and the client (browser) is through the Session. The Session is the only thing that is kept between requests. You can save variables in the Session for later (like the attempts and the lastLoginAttempt), and rely on the Session to see if a user is successfully logged in.
And how do the server keeps the session between requests if everything gets recreated in each request? through the session cookie. The server users a normal cookie to which it gives a special value (In the Servlet specification this cookie is JSESSIONID). When a request come without that cookie the server creates one giving it the value of a unique identifier. Next requests from the same browser will have that cookie, and the server will use the cookie to attach the session to every HttpServletRequest generated from requests from that browser. So in the brand new HttpServletRequest that is created in every request, the server injects into it the same HttpSession that was being used by the same JSESSIONID.

Retrieving data with JSP (JSTL) from a Java MVC and JDBC [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 4 years ago.
I'm new to Servlets and MVC web programming. So far I have developed a basic CRUD project and would like to add a search function. I would like to use a JSP file to communicate with the servlets and use the tag ( I'm having trouble wording the question, but I hope my code below will clear it up).
Part of My DAO
public List<Courses> getAllCourses() {
// TODO Auto-generated method stub
List<Courses> courseList = new ArrayList<Courses>();
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery( "select * from courses" );
while( resultSet.next() ) {
Courses course = new Courses();
course.setCourseid( resultSet.getInt( "courseid" ) );
course.setCoursename( resultSet.getString( "coursename" ) );
course.setFaculty( resultSet.getString( "faculty" ) );
course.setCourseSpecification( resultSet.getString( "courseSpecification" ) );
course.setDuration( resultSet.getInt( "duration" ) );
courseList.add(course);
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return courseList;
}
public void findCourse(Courses course) {
try { Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename=?" );
while( resultSet.next() ) {
Courses course1 = new Courses();
course1.setCourseid( resultSet.getInt( "courseid" ) );
course1.setCoursename( resultSet.getString( "coursename" ) );
course1.setFaculty( resultSet.getString( "faculty" ) );
course1.setCourseSpecification(resultSet.getString("courseSpecification"));
course1.setDuration( resultSet.getInt( "duration" ) );
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return;
}
Servelet
#WebServlet(name = "GetStudent", urlPatterns = {"/GetStudent"})
public class FindCourse extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB private CourseDao courseDAO;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Courses course = new Courses();
String coursename = request.getParameter("coursename");
Courses course1= courseDAO.getCourse(course, coursename);
request.setAttribute("Courses", course1);
request.getRequestDispatcher("findCourse.jsp").forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
JSP
<form action="FindCourse" method="GET">
<input type="text" name="coursename" />
<c:forEach var="course" items="${courses}">
<td>${course.coursename}</td>
I would love a good explanation of this code as most of it is taken from tutorials etc and I am very kean to learn. So I would like the form to take user input and retrieve the courses which match the query and display the course or possibly courses if more than one course match the name. At the moment I'm getting "resource not found" errors.
As a side question, if I'm allowed, what is the form of the data between the view and the controller? Is there a way of regulating it or forcing it to take JSON/XML? How could I make this simple MVC into a RESTFUL service? I don't expect complex answers just some pointers in the right direction. Overall I have found this very enjoyable and challenging. Thank you.
The servlet is the heart of your web application . It functions as the controller where user (http) requests are being processed and response is generated and sent back to the user (usually in the form of a JSP page but could also be an image, a pdf document, a JSON response or any other content corresponding to a predefined http MIME type).
Jsp pages basically serve two purposes: 1) They present the response content to the user and 2) They allow the user to input information that is sent to the server (and then either stored there or used for filtering so as to create different responses). A JSP page should normally not be abused and business logic should be placed into the servlet while the JSP page should only have a minimum JAVA code (this usually means that you will use JSTL and EL (Expression lanhuage) and try to avoid scriptlets as much as possible)
The model in your web application is the data you're working on. An example would be a simple POJO (e.g. Courses) which contains all the fields (and corresponding getters/setters methods) that the Course table has. Typically, the controller will through a DAO (or some other means) access this model and make changes to it.
Regarding data format, JSP is rendered on the server, so normal Java objects can be used between the servlet (controller) and JSP pages.
Of course, when you send data via a HTML form (as part of a JSP page), the form data will, by default, be sent in application/x-www-form-urlencoded format. (this would be the enctype attribute of the form element). If you're using a file upload as part of the form , you will have to set data format to multipart/form-data. (as far as I know, a browser should support only these two formats on input)
Now, when you're not using a browser and want to create a REST web service, you will have to do the serialization/deserialization manually. This will involve creating a HTTP client and making HTTP requests (GET/POST) against the URL of the REST service. The actual data will have to be serialized (as JSON, XML, application-x-www-form-urlencoded etc) and attached to the request. The response will have to be deserialized.
As far as user input processing is concerned, you should do something like
//servlet
String courseName = request.getParameter("coursename"); //get the argument
//and then modify the sql query
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename='"+courseName+"'";
Note that it would be much better to use a PreparedStatement than a Statement (because a PreparedStatement is faster and more secure (against sql injection attacks)
As for the error, post the entire stack trace.

make a simple login authentication using java class,servlet,jsp and session and database

I want to make a login process using mvc structure where i send userid and password from index.jsp page.If they match with the database value then it will go to the stater001.jsp.In index.jsp i've 2 fields userid and password from.I've post userid and pwd into LoginServlet servlet.
LoginServlet process userid , pwd making the instance of loginAuthentication class.loginAuthentication class checks whether userid and password exists in database or not with select query.I have also used setter getter classuser to set userid and pwd into session.I tried to do the whole login process in an organised way.But i'm stucked with error i couldn't under stand what is the problem please help me to solve this.First i tried it without using mvc pattern then it worked fine.But now it is not working.
Below is my previous code all process in one servlet
package DataAccess;
import DataAccess.dbconnector;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
String userid, pwd;
Connection connection = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Statement statement = null;
userid = request.getParameter("uname");
pwd = request.getParameter("pass");
try {
dbconnector dbc = new dbconnector();
connection = dbc.Open();
PreparedStatement ps = connection.prepareStatement("select * from member where uname='" + userid + "' and pass='" + pwd + "'");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("userid", userid);
response.sendRedirect("view/starter001.jsp");
} else {
request.setAttribute("errorMessage", "Invalid user or password");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
And in my new code here i've stucked with error in execution
And here i've attached my new edited codes where i tried to do this in an organised way .My errors have been gone but not showing the userid after login http://pastebin.com/RKyieMqn
Please consider my question
at first when all codes were in loginservlet then it was like but when i start using mvc structure it is not showing the username
Obviously, you pasted the wrong code:
In the below statement, where is the variable user defined?
session.setAttribute("user", user);
Perhaps, you have created a authenticateUser object somewhere. Please check you code to find it.
I have changed session.setAttribute("userid", user); to session.setAttribute("userid", user.getUserId()); and now it's working

How can I secure a JSP page after adding it to my hosting and making it live?

I have a very basic login JSP that passes the variables to the servlet and checks from a MySQL DB if the username and password are available. Is this secure enough to use on a website, or does it need more security? If so, how to make it more secure?
This is the servlet:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.*;
import java.sql.*;
/**
* Servlet implementation class loginServlet
*/
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #seeHttpServlet#HttpServlet()
*/
public loginServlet() {
super();
// TODOAuto-generated constructor stub
}
/**
* #seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODOAuto-generated method stub
}
/**
* #seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String email = request.getParameter("email");
String pwd = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",
"root", "password");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select fname, lname, email from userAccount where Email='"
+ email + "' and password='" + pwd + "'");
if (rs.next()) {
session.setAttribute("email", email);
session.setAttribute("Fullname", rs.getString(1) + " " + rs.getString(2));
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("fail.jsp");
}
} catch (Exception ssd) {
System.out.println(ssd.getMessage());
}
}
}
There are several security issues, and programming problems, with this code:
unless the application is served over HTTPS, the password passes in clear text over the network
passwords should not be stored in clear in a database. They should be salted using a random salt, and then hashed using a slow cryptographic algorithm like bcrypt. To check the password, you should salt and hash the input from the user, and compare the result with the salted and hashed password stored in the database
your code doesn't use prepared statements, opening itself to SQL injection attacks
your code doesn't use prepared stataments, which will make it fail, for example, as soon as there is a single quote inside the email or the password.
you shouldn't catch Exception. Only catch exceptions that you can handle, and that are supposed to happen. For unexpected exceptions, displaying a generic error page is fine. For expected exceptions, you should handle them. Your catch block logs something in the server console, and leaves the user with a blank page.
Is this secure enough to use on a website, or does it need more
security? If so, how to make it more secure?
No. this is not enough secure. You need to use form-based authentication, store password as hash and restrict direct resource invocation. For that, I prefer Spring Security. Following benefits you will get from Spring Security.
Basic Spring Security configuration
OpenID integration
Access Control List (ACL)
JDBC-based configuration
Remember-me services
LDAP-based authentication
Single Sign-on services
JSF and GWT integration
and many more
The above is insecure for the following reasons,
SQL Injection: If you see the below code, you are directly appending the user input to the SQL query. So lets say a user provided the email as "';drop table userAccount;". This would drop the table.
rs = st.executeQuery("select fname, lname, email from userAccount where Email='"+
email + "' and password='"+ pwd + "'");
Never show stack trace to user: If the code above throws any exception inside the try block, you are catching it and printing in console. But there is no response being sent. You can redirect the user to fail.jsp in that case as well.
Use Capcha or any token mechanism to avoid automated submissions.
It looks like your password is not hashed in the database. So before storing the password in the database call eg sha256 (https://stackoverflow.com/a/5531479/514463) and then when you are looking up the password in your above servlet do it again.
st.executeQuery("select fname, lname, email from userAccount where Email='"+ email + "' and password='"+ sha256(pwd) + "'");
Furthermore - you are not using bind variables in your sql so your code is open to sql injection which means someone could pass in as a password somehtlin like
"password; delete from users;"
and after your sql is executed the users table could all be deleted. Always use prepared statements
dbConnection.prepareStatement("select fname, lname, email from userAccount where Email=? and password=?" );
passing in your username and sha256(password)
You definitely should not store crear passwords so if you are hacked the hacker does not get the passwords.
You should digest them with a non-reversible algorithm (SHA-1 recommended) with salt.
Salt is a protection against rainbow tables.

simple HTML can't getJSON from servlet (java) + mysql

I am trying to get JSON from a simple HTML but I can't do it successfully :c .. I generate JSON from a java Servlet, from MySQL, like this ...
Prueba.java (Servlet)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
Connection conn = ConexionBD.obtenerConexion();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM grifo where id=1");
while(rs.next()){
String grifo = rs.getString("grifo");
String distrito = rs.getString("distrito");
String latitud = rs.getString("latitud");
String longitud = rs.getString("longitud");
JSONObject json = new JSONObject();
json.put("grifo", grifo);
json.put("distrito", distrito);
json.put("latitud", latitud);
json.put("longitud", longitud);
out.print(json);
}
} catch (Exception e){
out.print(e);
}
}
So, when I run this, I get the JSON:
{"grifo":"Grifo Libertad","distrito":"San Juan de Lurigancho",
"latitud":"-123.059028347924","longitud":"93.945783454234234"}
In my java project I have another page called index.jsp, that gets the JSON.
I get the json correctly, but when I create a .html (in desktop: file:///C:/Users/Jhonatan/Desktop/prueba.html in the web browser) with the same code:
http://freetexthost.com/w2xgabhaks
I can't get the JSON, just display NOTHING! Is there a problem with the file on the server (.jsp), at some other location (desktop: .html) or maybe with the database (mysql)?
How does https://graph.facebook.com/zombies work then?
Thanks for all of you!
Have you looked at what the JS console says? My guess is that it will throw something like Origin null is not allowed by Access-Control-Allow-Origin.
JavaScript requests have a same-origin policy. What you're trying to do is a cross-origin request.
The simple fix is for your server to return the following header:
Access-Control-Allow-Origin: *
But I recommend you read all about this and understand what are the implications.

Categories

Resources