2015-01-06 34 views
0

我嘗試輸入重複條目時出現問題,如下面的servlet中所示。問題是tomcat顯示重複的錯誤,但是servlet沒有重定向到所需的錯誤頁面(dup_organism.jsp)。但是,當我輸入新記錄並重定向到另一個頁面時,我沒有任何問題,而代碼幾乎相同。 我有這個servlet:控制檯上的servlet錯誤不會重定向到錯誤頁面

package package_ergasia; 

import java.sql.*; 
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 


public class AddOrganism extends HttpServlet 
{ 
@Override 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException 
    { 
    response.setContentType("text/html");  
    Connection connection= null;  
    String url = "jdbc:mysql://localhost:3306/"; 
    String dbName = "ergasia";  
    String user = "root"; 
    String password = "password"; 
    String org_id = request.getParameter("id"); 
    String oname = request.getParameter("oname");  


     try { 
      connection = DriverManager.getConnection(url + dbName, user, password); 


      Statement statement = connection.createStatement() ; 
      ResultSet resultset = statement.executeQuery("SELECT * FROM organism") ; 

      while(resultset.next()){ 

       if(resultset.getString("org_id").equalsIgnoreCase(org_id)){ 
        String contextPath= "http://localhost:8084/secured"; 
        response.sendRedirect(response.encodeRedirectURL(contextPath + "/dup_organism.jsp")); 
       } 


        else{ 
         PreparedStatement ps = connection.prepareStatement("INSERT INTO organism (org_id,organismName) VALUES (?,?)"); 
         ps.setString(1, org_id); 
         ps.setString(2, oname);      
         ps.executeUpdate(); 
         String contextPath= "http://localhost:8084/secured"; 
         response.sendRedirect(response.encodeRedirectURL(contextPath + "/all_organisms.jsp")); 
        } 
      } 

     } catch (SQLException e) { 
      e.printStackTrace();   
     } 
    } 
    @Override 
    public String getServletInfo() { 
     return "info"; 
    } 
} 

這是錯誤頁面dup_organism.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
     pageEncoding="ISO-8859-1"%> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <link rel="stylesheet" type="text/css" href="../CSS/mystyle.css"> 
    <title>Duplicate entry</title> 
    </head> 
<body> 
      <h1>Error</h1> 
      <% String org_id = request.getParameter("org_id"); %> 

      <h2><div align="center"> 
      <br><br><br> 
      Duplicate data <br> @Organism Id: 
      <% out.println(org_id); %> 
      </div></h2>  
</body> 
</html> 

瀏覽器顯示什麼(仍servlet頁面上)和tomcat顯示以下錯誤:com.mysql.jdbc .exceptions.MySQLIntegrityConstraintViolationException:爲'PRIMARY'鍵重複輸入'02'

回答

0

問題爲什麼您的空值是您使用response.sendRedirect創建請求和響應對象的新實例。您可以執行以下任一操作:

  1. 將其替換爲request.getRequestDispatcher(url);
  2. 在會話對象中設置Org_id並在jsp中檢索它。
+0

我無法得到第一個工作,但我設置會話對象後,它的作品就像一個魅力,謝謝。 –

相關問題