2010-08-13 46 views
2

我写了一个代码将用户添加到数据库中。当我们收到重复的条目时,我需要重定向到EmpInfo.jsp。我需要使用更多的例外,我也想知道如何重定向。如何接收2个或更多不同的例外?

response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    Connection conn = null; 
    String url = "jdbc:mysql://localhost:3306/"; 
    String dbName = "cervlet"; 
    String driver = "com.mysql.jdbc.Driver"; 
    String userName = "root"; 
String password = "1234"; 
int Empid =Integer.parseInt(request.getParameter("Empid").toString()); 
String Name = request.getParameter("Name").toString(); 
int Age =Integer.parseInt(request.getParameter("Age").toString()); 
int Salary =Integer.parseInt(request.getParameter("Salary").toString()); 
PreparedStatement stmt; 
try { 
Class.forName(driver).newInstance(); 
conn = DriverManager.getConnection(url+dbName,userName,password); 
System.out.println("Connected to the database"); 
//ArrayList al=null; 
//ArrayList userList =new ArrayList(); 
String query = "insert into employee set Empid='"+Empid+"',name='"+Name+"',Age='"+Age+"',Salary='"+Salary+"'"; 
stmt = (PreparedStatement) conn.prepareStatement(query); 
    int i = 0; 
try { 
    i = stmt.executeUpdate(query); 
    } 
    catch (SQLException e) { 
    String nextj = "/AddUser.jsp"; 
    RequestDispatcher rd = getServletContext().getRequestDispatcher(nextj); 
    rd.forward(request, response); 
    } 
    System.out.println("i="+i); 
System.out.println("query: " + query); 
//if(i==0) 
//{ 
    //String nextj = "/EmpInfo.jsp"; 
    //RequestDispatcher cd = getServletContext().getRequestDispatcher(nextj); 
    //cd.forward(request, response); 
//response.sendRedirect("servletRecord"); 
//} 
response.sendRedirect("/EmpInfo.jsp"); 
conn.close(); 
System.out.println("Disconnected from database"); 

} catch (Exception e) { 
e.printStackTrace(); 

更新

我需要重定向到EmpInfo.jsp,当它增加了一个新的条目。 执行方法executeUpadte()后,我使用其返回的 值重定向到另一页,名为EmpInfo.jsp。 但它不重定向。我正在使用eclipse。告诉我多种重定向.jsp页面的常用方法。

+0

与问题无关:因IllegalStateException异常导致转发/重定向失败,因为您已更改了响应头并在代码的开头获得了响应写入器。不要这样做。在这种特殊情况下绝对没有必要这样做。删除这些线。另外,您应该避免使用'PreparedStatement'进行SQL注入,并在'finally'中关闭JDBC资源。 – BalusC 2010-08-13 20:36:08

+0

你应该询问另一个问题的重定向。 – jjnguy 2010-08-14 02:29:57

+0

您是否阅读过我在问题更新前2小时发布的评论? :) – BalusC 2010-08-14 03:25:03

回答

9

好吧,如果你问如何捕捉不同的异常下面的代码是你怎么做:

try { 
    ... 
    // Code that may throw a few types of exceptions 
    ... 
} catch(FileNotFoundException fnfe) { 
    // handle very specific exceptions 
} catch (IOException ioe) { 
    // handle less specific exceptions 
} catch (Exception e) { 
    // handle the most generic exception case 
} 

这将允许你在一个代码块处理多种异常。

2

处理多个异常已被回答。

关于重定向到其他页面:您可以使用(因为您已经使用)转发方法(如果其他页面在同一个域中)和sendRedirect方法(其他页面可以在其他域中)。但是你需要注意,没有任何东西写入浏览器,否则在转发/重定向时你会遇到异常。

你的情况,你已经写入浏览器在这些语句的形式:

response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 

看你的代码,看来你甚至不需要这些语句,正如你应该转发到任何情况下,其他页面。

注意:您正在一个地方使用forward并在一个地方使用sendRedirect。希望你知道这些之间的差异。在我看来,你需要在两个地方都使用forward方法。

相关问题