Login class:
public static String n=request.getParameter("userName");
public static String p=request.getParameter("userPass");
Servlet class:
PreparedStatement ps1= con.prepareStatement("insert into "+Login.n+" values(?,?,?)");
In login class im using a html page where it shows name and password..so when ever user login it validates his pass by Loginps class and returns to login servlet where i placed html form are dress ,dou,pattern fileds ..here action given to servlet class where servlet class request parameters dress ,dou, pattern ...in preparedstatement("sql query have to insert into"+here i want string n value +"values (?,?,?)")
I want to use string n from Login class so that I can make a dynamic tables when user created his account.
Any help appreciated.
Login class:
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if("YOURSERVLETCLASS".checkUser(n, p))
{
// anything you like for example forwarding to welcome page
RequestDispatcher rs = request.getRequestDispatcher("welcome.html");
rs.forward(request, response);
}else {
// if not correct back to index page
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
Servlet class:
public static boolean checkUser(String n,String p){
boolean status=false;
try{
// set your connection here Connection con = .....
PreparedStatement ps=con.prepareStatement(
"INSERT INTO userdetails(username,password)"+"VALUES(?,?)");
ps.setString(1,n);
ps.setString(2,p);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
Related
This question already has answers here:
Passing parameter without use of HTML forms in JSP
(3 answers)
Closed 3 years ago.
I have been trying to pass the data from a JSP page to a Java Servlet without using form. The JSP form returns to itself (action="") and I validate the form element. Then I want to pass the inputs of the user to Java Servlet. Couldn't find a good solution. Is there any easy way?
I understand what you are looking for, if you want to pass parameters to Servlet without using form you can simple try this, but you need to add your parameters on the link
this is an example.
<a href="ServletName?theNameOfParameterToSend=TheValueOfTheParameter&anotherNameOfParameterToSend=TheAotherValueOfTheParameter>
this is real example
<a href="MyApp?currancy=usd&country=usa>Send</a>
By using this way you can't send data by String query in post, it will be always visible in the link.
Wish I was helpful.
Maybe you can try Ajax.
I use Ajax Asynchronous Verify that the account exists.
If the account does not exist, you will be prompted below.
It can pass data without refreshing the page.
Here is my related code.
public User getUserByName(String name) {
User user = null;
try {
conn = DBUtils.getConnection();
String sql = "select id,name,pwd from user_info where `name`=?";
statement = conn.prepareStatement(sql);
statement.setString(1, name);
resultSet = statement.executeQuery();
while (resultSet.next()) {
user = new User();
user.setName(resultSet.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, statement, resultSet);
}
return user;
}
public class CheckNameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
UserDao userDao = new UserDaoImpl();
User user = userDao.getUserByName(name);
PrintWriter pw = resp.getWriter();
if (user == null) {
pw.print(1);
} else {
pw.print(0);
}
}
}
<script type="text/javascript">
function checkName() {
var name = $("#name").val();
$.ajax({
type: "post",
url: "check",
data: {"name": name},
success: function (data) {
if (data == "0") {
$("#msg").html("");
} else {
$("#msg").html("The account does not exist, please re-enter!")
}
}
});
}
</script>
then put msg in your HTML.
Hope it can help you.
for a project I'm developing an app with web services
My problem concerns the login page, that is when I manage that the user has not registered, I would like to show an alert on the same login page..
#Path("postlogincookie")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postLoginAdminCookie(#FormParam("username") String username, #FormParam("password") String password)
{
java.sql.Connection con = null;
SqliteConnection sqlite = new SqliteConnection();
sqlite.setDbPath(dbPath);
con = sqlite.connect();
String query = "SELECT Username,Password,Role FROM User WHERE Username ='"+username+"' and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
if(!rs.next())
{
return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build();
}
currently I use return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build(); but I don't want to change page to give the error message.
is there a solution to give a message of alert or error on login page?
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.
I am trying to implement simple login system. I have a JSP with form where user enters username and password, and then servlet that is reading those parameters. You'll understand from servlet code:
User user = userDao.findUserWithUsernameAndPassword(username, password);
// user found
if (user!=null) {
session = request.getSession(true);
session.setAttribute("user", user);
loginMessage = "Welcome";
request.setAttribute("loginMessage", loginMessage);
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
} else // username and password not matching
{
loginMessage = "Wrong username or password! Please try again.";
request.setAttribute("loginMessage", loginMessage);
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
}
This works if I enter valid username and password, but if not I am getting next exception:
javax.persistence.NoResultException: Query "SELECT u FROM User u WHERE
u.username like :username AND u.password LIKE :password" selected no
result, but expected unique result.
What is the proper way of handling this situation? I would like for wrong username and password parameters to display appropriate message (forwarding in 'loginMessage' variable).
[added]This is the code in UserDAOBean:
#Stateless
#Local(UserDAOLocal.class)
#TransactionManagement(TransactionManagementType.CONTAINER)
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UserDAOBean extends GenericDAOBean<User, Integer> implements UserDAOLocal{
public User findUserWithUsernameAndPassword(String username, String password)
{
Query q = em.createNamedQuery("findUserWithUsernameAndPassword");
q.setParameter("username", username);
q.setParameter("password", password);
User result = (User) q.getSingleResult();
return result;
}
}
And named query in entity User is:
#NamedQuery(name = "findUserWithUsernameAndPassword", query = "SELECT
u FROM User u WHERE u.username like :username AND u.password LIKE
:password")
This Exception is throw by the entity manager when you call the method getSingleResult and there is no resul, so you need to change the findUserWithUsernameAndPassword method.
If you are searching the entity by it's Primary Key you could use the em.find, it method returns null if there is no result.
Another option is not use the getSingleResult() and use the getResultList() it will not throw the NoResultException if there is no result, you need to check if the list is empty if there is no result.
If you want to maintain your method you must to catch the Exception and implements the logic where there is no result.
The follwoing servlet snippet :
ResultSet set = statement.executeQuery();
// userName = set.getString(1);
if(set.next()) {
userName = set.getString("FirstName");
Email = set.getString("Email");
}
if(set.wasNull()) { //<<------------- line 33
// turn to the error page
response.sendRedirect("LoginFailure.jsp");
} else {
// start the session and take to his homepage
HttpSession session = request.getSession();
session.setAttribute("UserName", userName);
session.setMaxInactiveInterval(900); // If the request doesn't come withing 900 seconds the server will invalidate the session
RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
rd.forward(request, response); // forward to the user home-page
}
creates the following exceptions :
INFO: java.sql.SQLException: Invalid operation: wasNull() called with no data retrieved.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ResultSet.wasNull(Unknown Source)
at com.sun.gjc.spi.base.ResultSetWrapper.wasNull(ResultSetWrapper.java:141)
--------->> at projectcodes.ValidateDataForSignIn.doPost(ValidateDataForSignIn.java:33)
..........
Why does this exception occur ? The exception occurs due to the highlighted line : 33
This exception can occur when ResultSet#next() has returned false. I.e. there is no row at all and thus no column has been retrieved at all. The ResultSet#wasNull() only applies on the last retrieved column, not on the last retrieved row.
You need to rearrange your code logic.
if(set.next()) {
userName = set.getString("FirstName");
Email = set.getString("Email");
// start the session and take to his homepage
HttpSession session = request.getSession();
session.setAttribute("UserName", userName);
session.setMaxInactiveInterval(900); // If the request doesn't come withing 900 seconds the server will invalidate the session
RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
rd.forward(request, response); // forward to the user home-page
} else {
// turn to the error page
response.sendRedirect("LoginFailure.jsp");
}
More clear would be to refactor all that JDBC mess into a standalone UserDAO DAO class with a User model class which you then use as follows:
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
request.getRequestDispatcher("portfolio_one.jsp").forward(request, response);
} else {
response.sendRedirect("LoginFailure.jsp");
}
where the find() method look something like this:
public User find(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, firstname, lastname, FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getLong("id"));
user.setUsername(resultSet.getString("username"));
user.setEmail(resultSet.getString("email"));
user.setFirstname(resultSet.getString("firstname"));
user.setLastname(resultSet.getString("lastname"));
}
} finally {
close(resultSet, statement, connection);
}
return user;
}
This way you end up with more self-documenting and better reuseable/testable code.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern