我在jsp中创建了一个表单,并尝试使用Spring JDBC将表单详细信息发送到数据库。我创建了一个JSP表单,一个servlet文件db_Servlet.java用于从表单获取数据,db_Service.java用于将数据发送到数据库。
当我使用tomcat运行项目时,它在创建db_Service类的对象时会卡住。 下面的代码是db_Servlet.java的servlet doPost方法。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("entered the servlet");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String ph = request.getParameter("phone");
long phone = Long.parseLong(ph);
String emailid = request.getParameter("emailid");
customer c= new customer(name,phone,emailid);
try {
System.out.println("entered the try block");
db_Service service = new db_Service();
int result = service.addtodb(c);
System.out.println(result);
String title = "Thank you";
String doctype = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(doctype +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body>" +
"Thank you for wasting your precious time"
+ " </body></html>"
);
}
finally {
out.close();
}
}
以下是db_Service类
public class db_Service {
public void addtodb(customer c){
System.out.println("Entered the service");
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
JDBCtemplate customerJDBCtemplate =
(JDBCtemplate)context.getBean("JDBCtemplate");
customerJDBCtemplate.create(c.getName(),c.getPhone(),c.getEmailid());
}
}
评论&#34;进入服务&#34;注释&#34;进入试块&#34;
后不显示答案 0 :(得分:2)
您可以尝试在不使用servlet的情况下添加customer方法,例如:
public static void main(String[] args)
{
db_Service db = new db_Service();
customer c = new customer();
db.addtodb(c);
}
如果上面的代码不能正常工作,那么在代码的beans.xml中加载spring的模式可能会出现问题
答案 1 :(得分:-1)
如果您使用的是Spring,那么最好使用自动连线而不是手动创建bean对象。尝试这样的事情:
@Autowire
db_Service service;
同时向@service
添加db_Service
所需的注释。