I have a little problem.
In this code, always there is catch{} section firing. Even if any exception is thrown. I checked in debugger and no exception is THROWN but somehow code from catch{} is firing and it transfers me to google.com.
If I comment the code from catch{}, Page is running fine.
Someone know why is that? It makes me mad.
Thanks
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}
Response.Redirect can throw a ThreadAbortException. This then hits the outer exception handler, triggering the second Response.Redirect.
See Why Response.Redirect causes System.Threading.ThreadAbortException?
More importantly, this is one reason that data access code should not be mixed so tightly with UI behavior. Debugging such code is difficult, unit testing is near impossible, and reusability is low.
It also looks like your query is being constructed via string concatenation, which is vulnerable to SQL injection. Parameterize the query instead.
The overload of Response.Redirect you are using will always try and stop the current thread. This causes the exception you are seeing. System.Threading.ThreadAbortException
There is an overload available: Response.Redirect(string url, bool endResponse) that allows you to control whether to end the current thread using the endResponse parameter.
All that being said, you can catch this specific error and ignore it. The suggestion below is just one of a few solutions you can implement. It all depends on what you are trying to do.
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (System.Threading.ThreadAbortException)
{
//do nothing. This is an expected error stemming from Response.Redirect
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}
Related
I am trying to update my data base from the web but it doesnt work and I dont know why. it says: "Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
what do I need to do?
protected void button1_Click(object sender, EventArgs e)
{
string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" +
System.Web.HttpContext.Current.Server.MapPath(#"DataBase\Users.accdb");
string Query = "update Users.users set (aid,email) (id='" +
id_txt.Value.ToString() + "',email='" + email_txt.Value.ToString() + "'
where id='" + id_txt.Value.ToString() + "' ;";
System.Data.OleDb.OleDbConnection con = new
System.Data.OleDb.OleDbConnection(strConnection);
System.Data.OleDb.OleDbCommand cmd = new
System.Data.OleDb.OleDbCommand(Query, con);
System.Data.OleDb.OleDbDataReader myReader;
try
{
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
}
}
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.
There are other similar questions to this, but I don't feel like it answers mine. From a Java servlet I need to be able to ssh to any server on my company's network and dynamically handle this unknown key exception and then issue a command to get and display the current status of the server.
I saw one suggestion to use JSch session.setFingerprint, but it must have changed or something because far as I can tell, it doesn't exist. I'm using Netbeans.
Here's my code:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url = "validurl";
String user = "validuser";
String password = "validpassword";
printer.println ("HelloWorld!");
JSch ssh = new JSch();
ChannelShell ch = null;
Session session = null;
try {
session = ssh.getSession(user, "serverIP", 22);
session.setPassword(password);
session.connect();
ch = (ChannelShell)session.openChannel("shell");
ch.connect();
}
catch (JSchException e) {
System.out.println ("Exception: " + e);
}
catch (Exception e) {
System.out.println ("Exception: " + e);
}
Thanks!
Devin
I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on
page.redirect["master.apsx",true]
so I changed it to
page.redirect["master.aspx",false]
and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{
strconn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
Label1.Text = " conn string";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{
try
{
if (txt_username.Text != null)
{
if (txt_password.Text != null)
{
DataTable dt = new DataTable();
conn = new SqlConnection(strconn);
conn.Open();
cmd = new SqlCommand("Select * From UserMaster Where Username=#username and Password=#password", conn);
cmd.Parameters.AddWithValue("#username", txt_username.Text);
cmd.Parameters.AddWithValue("#password", txt_password.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
{
if (dt.Rows.Count > 0)
{
userloginname = txt_username.Text;
userloginpassword = txt_password.Text;
Session["username"] = txt_username.Text;
MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Response.Redirect("Marketing.aspx",false);
}
else
{
Label1.Text = "else part";
MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txt_username.Focus();
}
txt_username.Text = "";
txt_password.Text = "";
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
conn.Close();
Label1.Text = "login";
}
You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.
I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
You need to provide more detail
You need to check weather you are able to connect to database or not.
You also need to check weather the page is called or not (which comes after login).
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.