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

Posted

技术标签:

【中文标题】无法使用 JSP/DAO/Servlet 更新表【英文标题】:unable to update table using JSP/DAO/Servlet 【发布时间】:2011-12-23 09:22:06 【问题描述】:

您好,我正在尝试创建一个页面来更新我的数据库表中的一行我正在使用带有 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  id='table1'  border="1" cellspacing="2" cellpadding="2"> 
    <tr class="tab-highlighted-2"> 

        <td class="tab-highlighted-2" > 
          <div align="left">Name</div> 
        </td> 
        <td class="tab-highlighted-2" > 
          <div align="left">Age</div> 
        </td>
         <td class="tab-highlighted-2" > 
          <div align="left">Gender</div> 
        </td>
        <td class="tab-highlighted-2" > 
          <div align="left">Status</div> 
        </td>    
        <td class="tab-highlighted-2" > 
          <div align="left">Breed</div> 
        </td>  
        <td class="tab-highlighted-2" > 
          <div align="left">Pen #</div> 
        </td> 
        <td class="tab-highlighted-2" > 
          <div align="left">Zoo</div> 
        </td> 
        <td class="tab-highlighted-2" > 
          <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 Driver] 标准表达式中的数据类型不匹配。

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;


知道我的错误在哪里吗?

【问题讨论】:

离题了,但是如果您不编写任何 scriptlet 代码(您不是,也不应该编写),则您的 JSP 中不需要任何这些导入指令。 【参考方案1】:

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

  "update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = "
                  +Integer.parseInt(breedid)+" , remark = '"+remark+"' where animal_id = '"+id+"'"

如果 animal_id 也是数字,则需要相同。

【讨论】:

能否提供动物表的架构 你到底想要什么?因为访问生成的 shcema 有点大 你能在调试器中检查 db 上正在执行的更新查询是什么吗?尝试通过 sqldeveloper/SQL+ 或您使用的任何其他 GUI 工具执行该查询,如果它不工作只是相应地修复查询和代码 我删除了值周围的单个 qoutes,现在我得到 java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] 参数太少。预计 2. 你必须只删除那些在数据库中是数字的字段的单引号【参考方案2】:

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

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

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

【讨论】:

我删除了值周围的单个 qoutes,现在我得到 java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] 参数太少。预计 2. 它现在更新了我只需要摆脱 java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed 错误 @user1031152 有太多代码要我去处理。通过转发(如 JSP)或直接写入输出流,正在写入响应。一旦发生这种情况,您将无法发送重定向。

以上是关于无法使用 JSP/DAO/Servlet 更新表的主要内容,如果未能解决你的问题,请参考以下文章

MySQL 常用SQL查询语句

MySQL 常用SQL查询语句

MySQL 常用SQL查询语句

MySQL 常用SQL查询语句

选择或计算所有行时 Sql 表无响应

Django 自动建表无反应的解决方法