Getting the cannot callsendredirect() after the response has been committed - mysql

Again my question related with the same project which i am doing for the report tracking system getting the below error in the tomcat logs after accessing the login page which is redirect towards "userloginmid.jsp".The code as shown below in the same window.
Please provide the solution for the same if possible.
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "report_tracking";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "root";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "select * from userregister where username='"+userName+"' and password='"+password+"'";
out.println(strQuery);
ResultSet rs = st.executeQuery(strQuery);
if(rs.next())
{
int userid=rs.getInt(1);
String user=rs.getString(2);
session.setAttribute("userid",userid);
session.setAttribute("username",user);
session.setAttribute("intime",strDateNew);
String queryString = "INSERT INTO admin set userid="+userid+",intime='"+strDateNew+"'";
int i = st.executeUpdate(queryString);
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
}
response.sendRedirect("login.jsp");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>

As all said there are lot of loopholes in your code.
But the answer to your quesion is
sendRedirect requires a return statement
So change your lines of code to
response.sendRedirect( "welcome.jsp"); return; and
response.sendRedirect("login.jsp"); return;
Also read this .

There are a lot of problems with your code.
First, the explanation of your stated problem, redirecting after committing a response:
When the HTTP headers are already sent to the client (read about the HTTP protocol if you don't know it yet), they are out and cannot be pulled back. You're coding your sample in a jsp, which is the VIEW part of your architecture - and at least between the "page import" and the code part there's a newline which might trigger the server to flush its buffers to the client. Once that's done, the HTTP headers are gone and you cannot redirect any more.
Workaround: Don't implement this routine in a jsp, but in a servlet (or use a decent framework that handles this problem for you. Any of the current will suffice).
Now about some of the problems that your code has:
Please read about SQL injection. Think of someone posting
usernames like someone'; someone' OR '0' = '0 or similar (just
making them up as I go)
Once you get your connection and run in to any error, you won't clean
up the connection (e.g. you will leak connections on any exception)
You seem to be storing clear text passwords. Definitely a no-go as
soon as someone else than you will have an account

Related

Intellij MYSQl how to connect with controller class?

I'm new to intelliJ, just switched from eclipse. I have a few question:
I have gone to the project settings, to the libraries and added MYSQl connection. Also under modules and dependencies I have the mySql connector.
I have tried the following code in eclipse:
String dbUsername = "root";
String dbPassword = "12frimyux09";
String URL = "127.0.0.1";
String port = "3306";
String dbName = "university";
//Connection con;
String SQL;
String dbURL = "jdbc:mysql://" + URL + ":" + port + "/" + dbName + "?verifyServerCertificate=false&useJDBCComplaintTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
Properties property = new Properties();
property.setProperty ("user", dbUsername);
property.setProperty("password", dbPassword);
property.setProperty("useSSL", "false");
property.setProperty("autoReconnect", "true");
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection (dbURL, property);
worked just fine, but doesn't work with intellij (I put the code in the controller class), even tried using try and catch, still no luck, I get the following error.1
Also in eclipse when I use Integer.parseInt I get alot of suggestions, but with intellij I get error and no suggestions, tried cntrl space and cntrl p, also went to file, settings, code completion and set all the ticks under parameter info, what am I doing wrong, why isn't intellji completing me???

Inserting into mysql database using jsp throwing exception

I am trying to store information from a registration form page to the corresponding database but the code is throwing the exception as stated 'unable to connect to database' I am a beginner and having a hard time trying to figure out what's going wrong in this. Can somebody please help?
<%#page import="java.sql.*"%>
<html>
<head>
<meta charset="utf-8">
<title>Sign Up</title>
<link rel="stylesheet" type="text/css" href="reg.css">
</head>
<body>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String date = request.getParameter("date");
String sex = request.getParameter("sex");
Connection con = null;
PreparedStatement ps = null;
String connectionURL = "jdbc:mysql://localhost:3306/table";
String driverName = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
Class.forName(driverName).newInstance();
try {
con = DriverManager.getConnection(connectionURL, user, pass);
String queryString = "INSERT INTO detail(name,password,email,date,sex) VALUES (?,?,?,?,?)";
ps = con.prepareStatement(queryString);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, email);
ps.setString(4, date);
ps.setString(5, sex);
int updateQuery = ps.executeUpdate();
if (updateQuery != 0) {
out.println("Successful Registration");
}
}
catch (Exception ex) {
out.println("Unable to connect to database.");
}
finally {
// close all the connections.
ps.close();
con.close();
}
%>
</body>
</html>
Have you included driver jar file in your project ?
At String connectionURL = "jdbc:mysql://localhost:3306/table"; is table is your database name which you want to connect?
At
catch (Exception ex) {
out.println("Unable to connect to database.");
}
include ex.printStackTrace() which will show you exact error.
Well... "unable to connect to database" means exactly that. Your JSP could not connect to the database.
Please add the full stack trace (error) in your question. That way it will be clearer what the problem is.
Off the top of my head, the possible culprits are:
You don't have the driver loaded in your JEE container. Did you add the database driver?
Your driver is not properly configured. Did you specify the correct "driver class" when adding the driver?
Your URL is wrong. Please check the value of the URL. Is it well-formed? Follow the exact format as the example one and insert your specific values.
There's no database actually running at that HOST:PORT. Was the database created?
Your credentials are wrong, disabled, or don't even exist yet. Check your username and password with your DBA. Do you have the right ones?
So, if you have checked already that and you think you have all those good, check the connection using a standalone client first. That way you'll see if the connection can be established. I would recommend Squirrel SQL Client or Eclipse's Data Source Explorer. Give them a try to check you have the right parameters.
Once you check your connection with a local client, everything should work in the JEE container.

How do I use databases within ASP.Net

I've developed web applications in PHP for a few years and would like to learn about ASP.Net. I've installed VS2013 and have created an ASP.Net Web Application. I tried playing around with something that I found on wait for it W3Schools just because I knew it would be as simple as simple could be but it caused me some errors. I was trying to "connect" to an Access file in the wwwroot directory by using System.Data.OleDb but I had some problems.
My question is: Is there a simplistic way like in PHP where you have PHPMyAdmin to manage the database and then connect via something simple like $conn = new mysqli('localhost', 'user', 'password', 'db'); but for ASP.Net?
I'm struggling to find beginner level support for this on the web and would like to figure it out asap!
David, isnt's going to be "simple" as PHP, remember that VS2013 it's a server side language, more strong and complex.
I recommend to you the next:
Work with objects.
Here is some code may help you.
C#:
public System.Data.DataSet GetQuery(string _QueryComm){
System.Data.DataSet objResult = new System.Data.DataSet();
OleDbDataAdapter objAdapter;
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;";
objCon = new OleDbConnection(strProvider);
objCon.Open();
try
{
objAdapter = new OleDbDataAdapter(_QueryComm, objCon);
objAdapter.Fill(objResult);
objAdapter.Dispose();
objCon.Close();
}
catch (Exception e)
{
// Some exception handler
}
return objResult;}
Usage:
DataSet datainfo = GetQuery("select * from table");
VB:
Public Function GetQuery(strCommandQuery as String) As System.Data.DataSet
Dim objResult As System.Data.DataSet = New System.Data.DataSet
Dim objAdapter As OleDbDataAdapter
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;"
objCon = New OleDbConnection(strProvider)
objCon.Open()
Try
objAdapter = New OleDbDataAdapter(strCommandQuery, objCon)
objAdapter.Fill(objResult)
objAdapter.Dispose()
objCon.Close()
Catch ex As System.Exception
' Some exception handler
End Try
Return objResult End Function
Usage:
Dim datainfo as DataSet = GetQuery("select * From table")
Let me know if it's work for you.

JavaMail SMTPSendFailedException

I am writing a bulk email program using the JavaMail api. I have a Microsoft Exhange server which I am trying to send the emails in to. When I run my program I get the following error:
**com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.postMail(SendEmail.java:100)
at EmailGenerator.main(EmailGenerator.java:52)**
The part of my code trying to send the message is as follows:
Properties props = new Properties();
props.put("mail.smtp.host", email_server);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
class EmailAuthenticator extends Authenticator {
String user;
String pw;
EmailAuthenticator (String FROM, String PASSWORD)
{
super();
this.user = FROM;
this.pw = PASSWORD;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Session session = Session.getInstance(props, new EmailAuthenticator(USER, PASSWORD));
session.setDebug(debug);
System.out.println("Session created");
.. CREATED MESSAGE HERE...
Transport transport = session.getTransport("smtp");
transport.connect(exchange_server,user,password);
transport.send(msg);
transport.close();
I wonder am I missing some configuration on the Exchange server side, or is an issue with my code?
OK I figured out where I was going wrong here and am posting up the answer incase anybody else can get some value out of it. I had the following line of code:
props.put("mail.smtp.auth", true);
This was telling my application that it needed to authenticate to the SMTP server, when in fact it didnt. This was causing my application from logging into the SMTP server and sending the email and thus producing the error message. Setting this property to false or not having this line of code fixed the issue for me. This line of code is only necessary for SMTP servers that require you to login, which my Exchange server didnt.

What is the MySQL JDBC driver connection string?

I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.
Assuming your driver is in path,
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");
Here's the documentation:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
A basic connection string looks like:
jdbc:mysql://localhost:3306/dbname
The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).
"jdbc:mysql://localhost"
From the oracle docs..
jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]
host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
database is the name of the database to connect to. If not specified, a connection is made with no default database.
failover is the name of a standby database (MySQL Connector/J supports failover).
propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.
It is very simple :
Go to MySQL workbench and lookup for Database > Manage Connections
you will see a list of connections. Click on the connection you wish to connect to.
You will see a tabs around connection, remote management, system profile. Click on connection tab.
your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc.
where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
Construct the url accordingly and set the url to connect.
For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-
class DBConnection {
private static Connection con = null;
private static String USERNAME = "your_mysql_username";
private static String PASSWORD = "your_mysql_password";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/database_name";
public static Connection getDatabaseConnection(){
Class.forName(DRIVER);
return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers.
This was the way of loading class for JDBC driver for mysql
com.mysql.jdbc.Driver
But this is deprecated now. The new driver class is now
com.mysql.cj.jdbc.Driver
Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Here is a little code from my side :)
needed driver:
com.mysql.jdbc.Driver
download: here (Platform Independent)
connection string in one line:
jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false
example code:
public static void testDB(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
if (connection != null) {
Statement statement = connection.createStatement();
if (statement != null) {
ResultSet resultSet = statement.executeQuery("select * from test");
if (resultSet != null) {
ResultSetMetaData meta = resultSet.getMetaData();
int length = meta.getColumnCount();
while(resultSet.next())
{
for(int i = 1; i <= length; i++){
System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
}
}
resultSet.close();
}
statement.close();
}
connection.close();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
//db name:testdb_version001
//useSSL=false (get rid of MySQL SSL warnings)
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
String username="testdb";
String password ="testdb";
try{
System.out.println("Connecting to database :" +jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,username,password);
System.out.println("Connection Successful...!");
}catch (Exception e){
e.printStackTrace();
//e.printStackTrace();
}
}
}
The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
3306 is the default port for mysql.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ยป
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol
127.0.0.1: is the host and 3306 is the port number
test is the database
it's depends on what service you're using.
if you use MySQL Workbench it wold be some thing like this :
jdbc:mysql://"host":"port number"/
String url = "jdbc:mysql://localhost:3306/";
And of course it will be different if you using SSL/SSH.
For more information follow the official link of Jetbriens (intelliJ idea) :
Connecting to a database #
https://www.jetbrains.com/help/idea/connecting-to-a-database.html
Configuring database connections #
https://www.jetbrains.com/help/idea/configuring-database-connections.html
Check if the Driver Connector jar matches the SQL version.
I was also getting the same error as I was using the
mySQl-connector-java-5.1.30.jar
with MySql 8