JSP Servlet JDBC connection
843835Apr 19 2003 — edited Apr 20 2003Below is the code for handling login.
However I am new to servlets, and I am wondering is the code below correct?
Can anyone give me some advice if it is not correct?
------------------------------------------------------------------------
package gcd;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.mysql.jdbc.*;
public class LoginHandler extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//Load the driver
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the database
java.sql.Connection connection=java.sql.DriverManager.getConnection("jdbc:mysql://localhost/gcdBB_db");
//Create a statement object
java.sql.Statement statement = connection.createStatement();
Enumeration parameters = request.getParameterNames();
if(parameters.hasMoreElements())
{
// Get the user's account number, and password
String username = req.getParameter("username");
String password = req.getParameter("password");
statement.executeUpdate("INSERT INTO users (username,password) VALUES ('"+username+"','"+password+"')");
}
// Check the name and password for validity
if (!allowUser(username, password))
{
out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
out.println("<BODY>Your login and password are invalid.<BR>");
out.println("You may want to <A HREF=\"Login.jsp\">try again</A>");
out.println("</BODY></HTML>");
}
else
{
// Valid login. Make a note in the session object.
HttpSession session = req.getSession();
session.setAttribute("logon.isDone", account); // just a marker object
// Try redirecting the client to the page he first tried to access
try
{
String target = (String) session.getAttribute("login.target");
if (target != null)
{
res.sendRedirect(target);
return;
}
}
catch (Exception ignored) { }
// Couldn't redirect to the target. Redirect to the site's home page.
res.sendRedirect("/");
}
}
protected boolean allowUser(String username, String password)
{
return true; // trust everyone
}
}