how to avoid IllegalStateException [duplicate] - java

This question already has an answer here:
Avoiding java.lang.IllegalStateException in jsp
(1 answer)
Closed 8 years ago.
<%
String emi1;
String repo1;
String arr1;
String reso1;
String pi1;
emi1=request.getParameter("e"+count);
repo1=request.getParameter("repo"+count);
arr1=request.getParameter("a"+count);
reso1=request.getParameter("r"+count);
pi1=request.getParameter("pi"+count);
if(emi1!=null && repo1!=null && arr1!=null && reso1!=null && pi1!=null)
{
String ReserveDt = request.getParameter("ReserveDate");
System.out.println(emi1);
System.out.println(repo1);
System.out.println(arr1);
System.out.println(reso1);
System.out.println(pi1);
System.out.println(ReserveDt);
String sql=("BEGIN DECLARE #DT DATE;DECLARE #CIR NVARCHAR(2);SET #CIR='"+circle+"' DECLARE #MON NVARCHAR(2); DECLARE #DAY NVARCHAR(2); "
+"DECLARE #YEAR NVARCHAR(4);DECLARE #curr NVARCHAR(50); DECLARE #reg nvarCHAR(3);"
+"set #reg='"+utype+"' SET #DT='"+ReserveDt+"' SET #day=(SELECT DATEPART(day,#DT)) "
+"SET #MON=(SELECT DATEPART(month,#DT)) SET #year=(SELECT DATEPART(year,#DT)) "
+"SET #curr=#reg+convert(nvarchar(2),#DAY)+convert(nvarchar(2),#MON)+convert(nvarchar(4),#YEAR)+CONVERT(NVARCHAR(2),#CIR) "
+"INSERT INTO [DCRA].[dbo].[SAM]([REGION],[CIRCLE],[TOTAL],[EMI],[REPO],[REPO ARREAR],[RES],[CURR_DATE],[PI],[DATAID]) "
+"VALUES (#reg,#CIR,0.24,"+emi1+","+repo1+","+arr1+","+reso1+",'"+ReserveDt+"',"+pi1+",#curr) end");
System.out.println(sql);
stmt=con.createStatement();
stmt.executeUpdate(sql);
System.out.println(sql);
if("stmt"!=null)
{
response.sendRedirect("Add.jsp");
}
}
count++;
System.out.println(count+"my count");
}
}
catch(Exception e)
{
%>
<script type="text/javascript">
alert("Data is alredy insert or please check your data!");
</script>
<%
e.printStackTrace();
}
%>
I am very new into jsp , i am inserting the value into table that time it gives me error. I am showing data is added successfully in add.jsp.how to resolve this problem.please help me to resolve this problem.

i didnt find your try block without try you can not catch proper exception and also
put this line in your code
System.out.println(e.toString());
so that you get proper exception

Related

java.sql.SQLException: Column 'nombreGarcia' not found. why?

I cant connect my db with my java aplication and I really dont know whts wrong with it, comeone cant help me, please
try {
Connection miconexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/concesionario","root","password");
// 2.PASO CREAR PASO STAMENT.
Statement miStatement = miconexion.createStatement();
//3.PASO EJECUTAR MY SQL.
ResultSet miresulset = miStatement.executeQuery("SELECT * FROM CLIENTES");
//4.PASO RECORRER EL RESULSET
while(miresulset.next()) {
System.out.println(miresulset.getString("dni" + miresulset.getString("nombre" + "" + miresulset.getString("apellido"))));
}
}catch(Exception e) {
System.out.println("NO CONECTA");
e.printStackTrace();
}
This line
System.out.println(miresulset.getString("dni" + miresulset.getString("nombre" + "" + miresulset.getString("apellido"))));
adds whatever is found as apellido to "nombre". The value happens to be "Garcia", hence the String of nombreGarcia in the error. This is as far as I can go with helping you without further information from your part.

instead of catching Java MalformedURLException, build failing

New to Java, so please bear with me:
(and please note that this qestion is about Java Exceptions, not Jsoup)
when using Jsoup in order to get Html page: (Jsoup.connect(current_url._name).get();) , I tried to catch all possible 5 exceptions according to the Jsoup documentation: here
the program works fine with good URLs, but when I intentionally misspelled 1 URL to check what happens, I was surprised to see that the exception wasn't catch, instead the program start running, then the "Build failed"?
when only building the program there is no failure, so I think it isn't really
build issue.
here is the code:
// load html and check them:
for(URL current_url : URLs)
{
// no keyword - all getting 'yes'
if(keywords.isEmpty())
{
current_url._stat = URL_stat.YES;
}
// there are keywords - get pages and check them
else
{
Document html_doc;
// try to get document and catch all errors
try
{
html_doc = Jsoup.connect(current_url._name).get();
}
catch(MalformedURLException e)
{
System.out.println("the request " + current_url._name +
" URL is malformed");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(HttpStatusException e)
{
System.out.println("page " + current_url._name + " response"
+ " is not ok");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(UnsupportedMimeTypeException e)
{
System.out.println("page " + current_url._name+ " mime type"
+ " is not supported");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(SocketTimeoutException e)
{
System.out.println("connection to " + current_url._name +
" times out");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(IOException e)
{
System.out.println("an error occurred while getting page "
+ current_url._name);
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
// check if document has paragraphs, if not mark - no
}
}
and the output:
Exception in thread "main" java.lang.IllegalArgumentException: Malformed URL: ttp://cooking.nytimes.com/topics/what-to-cook-this-week
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:76)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at ex2.Ex2.main(Ex2.java:123)
Caused by: java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:74)
... 3 more
C:\Users\Administrator\AppData\Local\NetBeans\Cache\8.2\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
Thanks,
It is because the first exception being thrown is an IllegalArgumentException, which you have not defined in any of your catch clauses, thus preventing you from getting your custom error messages in any other catch blocks.

Selenium Try/Catch Error

I am using Selenium with Java an facing the following problem.
When I use the following code:
driver.findElement(By.xpath(firstNameXPath)).sendKeys(firstName);
I am able to successfully select the appropriate locator on the page and get no errors.
However, when I pass the locator to a method to check if the locator exists first and only then send keys I always get an error (locator not being present).
This is the method I am using:
public boolean IsXPathPresent(String XPath)
{
try
{
driver.findElement(By.xpath(XPath));
System.out.println("Selector: " + XPath + " found");
return true;
} catch (Exception e)
{
System.out.println(XPath + " Selector Not Present");
return false;
}
}
I am passing firstNameXPath to the method IsXPathPresent.
For some reason my program always outputs "Selector Not Present" which means it is always executing the catch part. But why ? The selector is present on page..
Is there something wrong with my try/catch block?
Thanks

java check condition after clicking on save button before commit

i want to put if else or switch statement which is more suitable for checking employee count before commit.where i put my if else or switch code . i want restriction on employee if count is 5 then its show message "reached maximum employee limites" otherwise allow commit.
i am new in java plz someone help me to solve this
public String cmdSave_action()
{
// my code before
{
DeptSet result;
try {
dbo.connect();
result =
dbo.execSQL("select count(*) from empmasterinfo where mainid='ORGElement' and designationid='?') "
(inputText_ORGElement.getValue() != null ?
""));
result = dbo.execSQL(sSQL);
catch (Exception e) {
System.out.println(e.getMessage());
finally
{
dbo.close();
}
return null;
}}}
// my code above
{
Global.PerformIteratorAction(this.bindings, "Commit");
AdfFacesContext afContext = AdfFacesContext.getCurrentInstance();
afContext.getProcessScope().put("EmployeeID",
Global.getCurrRowFieldValue("EmpmasterinfoViewIterator",
"Employeeid"));
if (afContext.getProcessScope().get("AddEdit").toString().equals("0"))
{
Global.PerformIteratorAction(this.bindings,
"EPR_TRANSFER_APPLICANT_INFO");
Global.PerformIteratorAction(this.bindings, "eprGenerateApPlan");
}
return null;
}}
My Error Log
Error(149,12): 'try' without 'catch' or 'finally'
Error(154,36): , expected
Error(157,34): field SQL not found in class hcm.view.backing.empprofile.EmployeeMasterInfo_Add
Error(159,11): illegal start of expression
Error(159,11): ; expected
E:\HCM\ViewController\src\hcm\view\backing\empprofile\dbo.java
Error(13,16): method does not return a value
Please close Your try catch block properly
try{
}catch(Exception e){
}finally{
}
And Read this
catch and finally are within try block
try {
//code
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
dbo.close();
}
Using an IDE will help you with indentation and proper formatting while writing code. e.g Eclipse.
For the first error close the try-catch blocks properly
And for the second error: Since your method is declared as public String cmdSave_action(), you should return a String value at the end of the method. The return statement is missing in your code.

Getting response from servlet

I'm using the following code to get the response from a servlet. It will check whether the given name in the variable "get" is in a particular table, and print 1 if it exists.
Portion of servlet code:
get = request.getParameter("nam");// such as get="kannan"
try {
// Connection code
ResultSet rs = stmt
.executeQuery("select * from newfarmer where rname='" + get
+ "'");
while (rs.next()) {
username = rs.getString("rname");
if (get.equals(username)) {
out.println(1);
}
}
} catch (Exception e) {
out.println(e.toString());
}
In my android application, I check this response as follows:
response = CustomHttpClient.executeHttpPost(
"http://moberp.svsugar.com:8080/androidservlt/Modify",
postParameters);
String res = response.toString();
res = res.trim();
if (res.equals("1")) {
flag = 1;
Toast.makeText(getBaseContext(), "Correct", Toast.LENGTH_LONG)
.show();
} else {
flag = 2;
Toast.makeText(getBaseContext(), "please enter correct Ryot name",
Toast.LENGTH_LONG).show();
}
It works very well for single record. I mean, in the table "newfarmer", If "rname" consists of more than one same name only the else part is executed.
Example:
If "kannan" is presented 2 times in the table Servlet output is as
1 1
Now in android application, clearly the else part is executed because response is not 1.
This is only case of two same names. The table may contains more than 10 same names.
If 10 same names, then servlet output is as
1 1 1 1 1 1 1 1 1 1
So I need to check all.
So I need to make changes in my if condition, but I don't know what to do. Someone please give answer.
Thanks in advance
instead of while loop Use
if(rs.next())
Now it will print only one time.
No change in android
in servlet do this
if(rs.next())
{
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
}
this loop will run only 1 time now if the record is present.
I don't understand why would get.equals(username) will evaluate to false when you are having a where clause in your SQL query?
So just try this.
if(rs.next())
{
// The above condition will make the code inside if executed
// only if any matching record is found and
//hence it will print `1` only once
//if any matching record is found.
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
Also you are using stmt.executeQuery("select * from newfarmer where rname='"+get+"'");
which is susceptible to SQL injection.
So better use prepared statement instead.
try if(rs.next()),
this will surely help you

Categories