Struts中数据库连接期间的java.lang.NullPointerException [英] java.lang.NullPointerException during database conectivity in struts
问题描述
我正在struts中建立数据库连接并得到error:javax.servlet.ServletException: java.lang.NullPointerException
,代码:-
config.xml:
Hi, I am making database connectivity in struts and getting error:javax.servlet.ServletException: java.lang.NullPointerException
, code:-
config.xml:
<form-beans>
<form-bean name="DemoTestForm" type="DemoTestForm"/>
</form-beans>
<action-mappings>
<action input="/index.jsp" name="DemoTestForm" parameter="testMethod" path="/test" scope="request" type="DemoTestAction">
<forward name="success" path="/welcomeStruts.jsp"/>
<forward name="fail" path="/Failure.jsp"/>
</action>
</action-mappings>
DBConnect.java:
DBConnect.java:
import java.sql.*;
public class DBConnect
{
Connection con=null;
String result;
public String checkUser(String name,String pass)
throws Exception
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
("jdbc:oracle:thin@localhost:1521:xe", "system", "java");
}catch(ClassNotFoundException cnf)
{
cnf.getMessage();
}
finally
{
con.close();
}
return(result);
}
}
DemoAction.java:
DemoAction.java:
public class DemoTestAction
extends org.apache.struts.action.Action {
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
DemoTestForm f = (DemoTestForm)form;
String name = f.getTextName();
String pass = f.getTextPass();
String logic=null;
DBConnect db=new DBConnect();
db.checkUser(name, pass);
Statement stmt=null;
ResultSet rs=null;
stmt=db.con.createStatement();
rs=stmt.executeQuery("select * from admin");
while (rs.next())
{
pass.equals(rs.getString(3))))
if (name.equals(rs.getString(2)) && pass.equals(rs.getString(3))) {
logic="success";
break;
}
else
{
logic="fail";
}
}
return mapping.findForward(logic);
}
}
index.jsp:
index.jsp:
<html:form action="/test">
Name: <html:text property="textName"/><br>
Password: <html:password property="textPass"/><br>
<html:submit property="loginButton" value="Login Here"/>
</html:form
>
请帮助解决我的问题.
Please help solve my problem.
推荐答案
请看以下代码:
Look at the following code:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
("jdbc:oracle:thin@localhost:1521:xe", "system", "java");
}
catch (ClassNotFoundException cnf) {
cnf.getMessage();
}
finally
{
con.close();
}
return(result);
每次执行代码时,都会执行finally
块.它在try
块之后需要清理,并且无论是否存在异常都将执行.
因此,在打开数据库连接后,请关闭它.
另外,即使不使用它,也不会设置result
.
Every time the code is executed the finally
block is executed. It is there to clean up after a try
block and is executed irrespective of if there has been an exception or not.
So after opening a DB connection you close it.
Also, even though it''s not used, result
is not being set.
这篇关于Struts中数据库连接期间的java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!