无法使用JSP / DAO / Servlet更新表

时间:2011-11-07 04:58:56

标签: java jsp servlets dao

您好我正在尝试创建一个页面来更新我的数据库表中的一行我正在使用带有JSP页面的DAO / Servlet

DAO代码:

public static AnimalUpdateBean updateAnimal(AnimalUpdateBean bean) {

          //preparing some objects for connection 
        PreparedStatement up = null;   
        Statement stmt = null;    

          String id = bean.getAnimalId();
          String aname = bean.getAnimalName();
          String dob = bean.getAnimalDob();  
          String gender = bean.getAnimalGender();  
          String breedid = bean.getAnimalBreed();  
          String remark = bean.getAnimalRemark();
          try 
           { 
            //connect to DB 
              currentCon = dbConnection.getConnection();

              up = currentCon.prepareStatement("update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = '"
                      +breedid+"' , remark = '"+remark+"' where animal_id = '"+id+"'");

              up.executeUpdate();

              if (up.executeUpdate()>=1){
                  stmt=currentCon.createStatement();
                  rs = stmt.executeQuery("select aname , dob, gender, specie_id , remark from animal where animal_id = '"+id+"'");
              }


          System.out.println("done");
       }


       catch (Exception ex) 
       {
          System.out.println("Log In failed: An Exception has occurred! " + ex);
       } 

       //some exception handling
       finally 
       {
          if (rs != null)   {try {rs.close();} catch (Exception e) {} rs = null;}

          if (stmt != null) {try {stmt.close();} catch (Exception e) {}stmt = null;}

          if (currentCon != null) {try {currentCon.close();} catch (Exception e) {}currentCon = null;}
       }

    return bean;

       }    
   }

UpdateAnimal.jsp代码:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@ page session="true"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%@page import="javax.servlet.*"%>
<%@ page language="java" 
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Update Animal</title>
<link rel="stylesheet"
      href="./css/styles.css"
      type="text/css"/>
</head>
<body>
<table class="title">
  <tr><th>Zoo keeper</th></tr>
</table>


<h1>Update Animal</h1>

<form action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>

<br>
Animal new gender: 
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>

Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">

</textarea> <br /> <br/>


<input type="submit" value="submit">
<input type="hidden" name="animal_id" value="<%= request.getParameter("animal_id") %>">
<input type="hidden" name="command" value="UpdateAnimalServlet" > 

</fieldset>
</form>
</body></html>

正在更新的记录来自一个选择页面,当用户点击他将被重定向到更新页面的名称时查看记录CheckAnimal.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@ page session="true"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%@page import="javax.servlet.*"%>
<%@ page language="java" 
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
      href="./css/styles.css"
      type="text/css"/>
</head>
<body>
<table class="title">
  <tr><th>Zoo keeper</th></tr>
</table>


<h1>Animal list</h1>
Click on animal name to update it!
 <center>
 <table width="100 % " id='table1'  border="1" cellspacing="2" cellpadding="2"> 
    <tr class="tab-highlighted-2"> 

        <td class="tab-highlighted-2" width="15"> 
          <div align="left">Name</div> 
        </td> 
        <td class="tab-highlighted-2" width="13"> 
          <div align="left">Age</div> 
        </td>
         <td class="tab-highlighted-2" width="13"> 
          <div align="left">Gender</div> 
        </td>
        <td class="tab-highlighted-2" width="13"> 
          <div align="left">Status</div> 
        </td>    
        <td class="tab-highlighted-2" width="13"> 
          <div align="left">Breed</div> 
        </td>  
        <td class="tab-highlighted-2" width="13"> 
          <div align="left">Pen #</div> 
        </td> 
        <td class="tab-highlighted-2" width="15"> 
          <div align="left">Zoo</div> 
        </td> 
        <td class="tab-highlighted-2" width="20"> 
          <div align="left">Remarks</div> 
        </td> 

    </tr> 

    <c:forEach items="${beans}" var="view"> 
        <tr> 

            <td><a href="/oosd/UpdateAnimal.jsp?animal_id=${view.animalId}&breed=${view.breedId}">${view.animalName}</a></td>  
            <td>${view.animalDob}</td>
            <td>${view.animalGender}</td>
            <td>${view.animalSource}</td>
            <td>${view.animalBreed}</td>
            <td>${view.sectionId}</td>
            <td>${view.zooId}</td>
            <td>${view.animalRemark}</td>

        </tr> 
    </c:forEach> 
</table> 

         </center>

</body></html>

AnimalUpdateBean.java代码:

package content;

public class AnimalUpdateBean {
    private String animalId;
    private String animalName;
    private String animalDob;
    private String animalGender;
    private String animalBreed;
    private String animalRemark;

    public String getAnimalId() {return animalId;}
    public String getAnimalName() {return animalName;}
    public String getAnimalDob() {return animalDob;}
    public String getAnimalGender() {return animalGender;}
    public String getAnimalBreed() {return animalBreed;}
    public String getAnimalRemark() {return animalRemark;}

    public void setAnimalId(String animalId) {this.animalId = animalId;}
    public void setAnimalName(String animalName) {this.animalName = animalName;}
    public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
    public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
    public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
    public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}


}

负责启动更新的servlet是UpdateAnimalServlet:

package content;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public class UpdateAnimalServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) 
                       throws ServletException, java.io.IOException {

try
{       

     AnimalUpdateBean animal = new AnimalUpdateBean();
     animal.setAnimalId(request.getParameter("animal_id"));
     animal.setAnimalName(request.getParameter("aname"));
 //    animal.setAnimalDob(request.getParameter("dob"));
     animal.setAnimalGender(request.getParameter("gender"));
     animal.setAnimalBreed(request.getParameter("breedid"));
     animal.setAnimalRemark(request.getParameter("remark"));
     String test = request.getParameter("animal_id");
     System.out.println(test);
     System.out.println(animal);

     animal = DAO.updateAnimal(animal);


          response.sendRedirect("/oosd/member.jsp"); 


} 


catch (Throwable theException)      
{
     System.out.println(theException); 
}
       }
    }

我正在使用一个调用AnimalUpdateServlet执行的Relay servlet:

package content;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class Relay extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) 
                       throws ServletException, java.io.IOException {

    try
    {       



        String command = request.getParameter("command");  
        if (command.equals("LoginServlet")){ 
            RequestDispatcher rd =request.getRequestDispatcher("/"+command);
            rd.forward(request, response);
            //for testing 
            System.out.println("Request forwarded to " + command + " servlet"); 
        } else if (command.equals("UpdateAnimalServlet")){ 
            RequestDispatcher rd =request.getRequestDispatcher("/"+command);
            rd.forward(request, response);
            //for testing 
            System.out.println("Request forwarded to " + command + " servlet"); 
        } 

        else 
            System.out.println("=> command='" + command + "'");  
            String url = "/oosd/" + command;     
            String encodedUrl = response.encodeRedirectURL(url);   
            System.out.println("   url=" + url);    
            System.out.println("   encodedUrl=" + encodedUrl);  
            response.sendRedirect(encodedUrl);



    } 


    catch (Throwable theException)      
    {
         System.out.println(theException); 
    }
           }
        }


and last thing is the web.xml page:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>content.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>UpdateAnimalServlet</servlet-name>
    <servlet-class>content.UpdateAnimalServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>SelectAnimalServlet</servlet-name>
    <servlet-class>content.SelectAnimalServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>Relay</servlet-name>
    <servlet-class>content.Relay</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SelectAnimalServlet</servlet-name>
    <url-pattern>/SelectAnimalServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UpdateAnimalServlet</servlet-name>
    <url-pattern>/UpdateAnimalServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Relay</servlet-name>
    <url-pattern>/Relay</url-pattern>
  </servlet-mapping>
</web-app>

我一直收到这些错误: 登录失败:发生异常! java.sql.SQLException:[Microsoft] [ODBC Microsoft Access驱动程序]条件表达式中的数据类型不匹配。

java.lang.IllegalStateException:在提交响应后无法调用sendRedirect()

我已经检查了数据条目和所有正确的名称文本,性别文本,specie_id号码,备注文本我甚至把dob保留到这个工作我正在使用访问数据库,这里是连接代码:

package content;


import java.sql.*;


public class dbConnection {

   static Connection con;
   static String url;

   public static Connection getConnection()
   {

      try
      {
         String url = "jdbc:odbc:oosd"; 
         // assuming "DataSource" is your DataSource name

         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

         try
         {              
            con = DriverManager.getConnection(url,"",""); 

         // assuming your SQL Server's  username is "username"               
         // and password is "password"

         }

         catch (SQLException ex)
         {
            ex.printStackTrace();
         }
      }

      catch(ClassNotFoundException e)
      {
         System.out.println(e);
      }

   return con;
}
}

知道我的错误在哪里?

2 个答案:

答案 0 :(得分:2)

因为specie_id是一个数字,而抛出的异常就是“条件表达式中的数据类型不匹配”。并且由于此异常发生了sendRedirect错误,因为SQLException数据已经写入响应。  您的查询应该是

  "update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = "
                  +Integer.parseInt(breedid)+" , remark = '"+remark+"' where animal_id = '"+id+"'"
如果animal_id也是一个数字,那么

也是必需的。

答案 1 :(得分:0)

当您已经将数据写入响应时(例如直接转发或直接写入JSP编写器)然后尝试重定向,就会发生sendRedirect错误。

SQL错误可能是由于您在SQL中使用字符串ID(由单引号括起来),而DB中的ID很可能被定义为整数。

此外,在更新动物后,您执行查询,但不对结果执行任何操作。