2013-12-02 2 views
0

У меня есть программа, которая записывает новую информацию сотрудника в текстовый файл. У меня есть проект, в котором я должен адаптировать указанную программу в одну, которая вводит эту информацию в базу данных Oracle. Я помещаю информацию и нажимаю кнопку отправки, тогда ничего не происходит, даже сообщение об ошибке или исключение. Я понятия не имею, что не так, или где даже начать искать, и я могу признать, что я немного передо мной. Я вполне уверен, что проблема связана с сервлетом. Вот мой код:Servlet не исполняет

form.jsp:

<%@page session="false" import="java.util.Iterator"%> 

<%-- Retrieve the Status bean from the Request scope --%> 
<jsp:useBean id="status" scope="request" class="util.Status"/> 

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Project 1</title> 
    </head> 
    <body> 
     <h1>Employee Hiring Form</h1> 

     <%-- Display any errors from previous form submission. --%> 
     <c:if test="${!status.isSuccessful}"> 
      <font color="red">There were problems processing your request:  
       <ul> 
        <c:forEach var="ex" items="${status.exceptions}"> 
         <li> 
          <c:out value="${ex.message}"></c:out> 
         </li> 
        </c:forEach>   
       </ul> 
      </font>  
     </c:if> 

     <%-- Display the form to enter a new hire. --%> 
     <form  action="C:\Users\Nelle\Documents\NetBeansProjects\EmployeeDB\src\java\web\HiringServlet" method="POST"> 
      <label for="department"><strong>Department</strong></label><br /> 
      <select name="department"> 
       <%String department = request.getParameter("department"); if (department == null) {department = "";}%>  
       <option value="unknown" <%if(department.equals("unknown")){out.print(" selected");}%>>Select a department...</s:option> 
       <option value="Human Resources" <%if(department.equals("Human Resources")){out.print(" selected");}%>>Human Resources</s:option> 
       <option value="Software Development" <%if(department.equals("Software Development")){out.print(" selected");}%>>Software Development</s:option> 
       <option value="Media Relations" <%if(department.equals("Media Relations")){out.print(" selected");}%>>Media Relations</s:option> 
      </select><br /><br /> 

      <%String name = request.getParameter("name");if (name==null) name="";%> 
      <label for="name"><strong>Employee Name</strong></label><br /> 
      <input type="text" name="name" value="<%=name%>" /><br /><br /> 

      <%String jobTitle = request.getParameter("jobTitle");if (jobTitle == null) jobTitle = "";%> 
      <label for="jobTitle"><strong>Job Title</strong></label><br /> 
      <input type="text" name="jobTitle" value="<%=jobTitle%>" /><br /><br /> 

      <%String yearHired = request.getParameter("yearHired");if (yearHired == null) yearHired = "";%> 
      <label for="yearHired"><strong>Year Hired</strong></label><br /> 
      <input type="text" name="yearHired" value="<%=yearHired%>" /><br /><br /> 

      <%String gender = request.getParameter("gender");if (gender == null) gender = "";%> 
      <label for="gender"><strong>Gender</strong></label><br /> 
      <input type="text" name="gender" value="<%=gender%>" /><br /><br /> 

      <input type="submit" value="Add Employee" /> <input type="reset" value="Reset" /> 
     </form> 

    </body> 
</html> 

confirmation.jsp:

<jsp:useBean id="department" scope="request" class="domain.Department"/> 
<jsp:useBean id="employee" scope="request" class="domain.Employee"/> 
<jsp:useBean id="hiringList" scope="request" class="java.util.ArrayList"/> 

<%@page contentType="text/html" pageEncoding="UTF-8" session="false" %> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Project 1</title> 
    </head> 
    <body> 
     <h1>New Hire Successfully Added</h1> 
     <p> 
      <strong>Employee Information</strong><br /><br /> 
      Name: <jsp:getProperty name="employee" property="name"/><br /> 
      Job Title: <jsp:getProperty name="employee" property="jobTitle"/><br /> 
      Year Hired: <jsp:getProperty name="employee" property="yearHired"/><br /> 
      Gender: <jsp:getProperty name="employee" property="gender"/><br /><br /> 

      Added to department: <jsp:getProperty name="department" property="name"/><br /> 
     </p> 

     <form action="form.jsp" method="POST" style="margin-bottom:25px;"> 
      <input type="submit" value="Add Another Employee" name="more" /> 
     </form> 

     <hr /> 

     <h2>Complete Employee List</h2> 
     <table> 
      <tr><td>Name</td><td>Job Title</td><td>Year Hired</td><td>Gender</td> <td>Department</td><td>Department Description</td></tr> 
      <c:forEach var="hire" items="${hiringList}"> 
       <tr> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getEmployee().getName()}"></c:out></td> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getEmployee().getJobTitle()}"></c:out></td> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getEmployee().getYearHired()}"></c:out></td> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getEmployee().getGender()}"></c:out></td> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getDepartment().getName()}"></c:out></td> 
        <td style="border:1px solid #ccc;padding:0 15px 0 5px;"><c:out value="${hire.getDepartment().getDescription()}"></c:out></td> 
       </tr> 
      </c:forEach> 
     </table> 
    </body> 
</html> 

HiringServlet.java:

(imports removed) 

public class HiringServlet extends HttpServlet { 

public Statement statement; 

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException { 

     response.setContentType("text/html;charset=UTF-8"); 
     PrintWriter out = response.getWriter(); 

     //Declare the dispatcher for the View 
     RequestDispatcher view = null; 

     //Create the business logic object 
     HiringService hs = null; 

     //Create the Status object and store it in the request 
     //for use by the 'Registration Form' View (if necessary) 
     Status status = new Status(); 
     request.setAttribute("status", status); 

     //Retrieve the HTML form parameters 
     String departmentName = request.getParameter("department"); 
     String name = request.getParameter("name"); 
     String jobTitle = request.getParameter("jobTitle"); 
     String yearHired = request.getParameter("yearHired"); 
     String gender = request.getParameter("gender"); 

     // Verify form fields data; create Exception objects if data are missing 
     if (departmentName.equals("unknown")) 
      status.addException(new Exception("Please select a department. ")); 
     if ((name == null) || (name.length() == 0)) 
      status.addException(new Exception("Please enter the employee name. ")); 
     if ((jobTitle == null) || (jobTitle.length() == 0)) 
      status.addException(new Exception("Please enter the job title. ")); 
     if ((yearHired == null) || (yearHired.length() == 0)) 
      status.addException(new Exception("Please enter the year hired. ")); 
     if ((gender == null) || (gender.length() == 0)) 
      status.addException(new Exception("Please enter the gender. ")); 

     // In case of errors, forward the request back to 'Registration Form' 
     // View and return without proceeding with the rest of the business logic. 
     if(!status.isSuccessful()){ 
      view = request.getRequestDispatcher("form.jsp");    
      view.forward(request, response); 
      return; 
     } 

     //If no verification errors are found, the Controller 
     //uses the business services to perform the registration. 
     try { 

     // Load the JDBC driver 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     System.out.println("Driver loaded"); 

     // Establish a connection 
     Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@nova.umuc.edu:1521:acad", "username", "password"); 
     System.out.println("Database connected"); 

     // Create a statement 
     statement = connection.createStatement(); 

      hs = new HiringService(); 

      // Retrieve the department object and verify that it exists. 
      Department department = hs.getDepartment(departmentName); 

      if (department == null) throw new Exception("The department you have "+ 
       " selected does not yet exist; please select another one."); 

      //Create and populate the employee object 
      Employee employee = hs.createEmployee(
       name, jobTitle, yearHired, gender); 

      //Delegate hiring to the HiringService object. 
      Hiring newHire = new Hiring(employee, department); 
      hs.hire(newHire); 

      ArrayList hiringList = hs.getHirings(); 

      request.setAttribute("department", department); 
      request.setAttribute("employee", employee); 
      request.setAttribute("hiringList", hiringList); 

      // Select the next View for the user in case hiring is 
      // successful Forward to the confirmation.jsp View  
      view = request.getRequestDispatcher("/confirmation.jsp");   
      view.forward(request,response); 
     } 

     catch (Exception ex){ 
      status.addException(ex); 

      //Select next View. 
      //Exceptions are caught, forward back to the form.jsp View. 
      view = request.getRequestDispatcher("/form.jsp");   
      view.forward(request,response); 
     } 

     finally {    
      out.close(); 
     } 
    } 
} 

Если вы хотите увидеть любой из моих другие документы .java, дайте мне знать, и я опубликую их, но я не думаю, что это проблема.

+0

Где 'HiringServlet.class' развернуто? Это действительно ниже 'src'? –

+0

На самом деле, я переместил HiringServlet в <пакет по умолчанию> и теперь он отправляет. Я знаю, что ты не должен этого делать, но это единственное, что сработало. Теперь мне просто нужно работать над отображением страницы подтверждения:/ – user2302019

+0

С пакетом вам просто нужна правильная структура каталогов. –

ответ

0

Я хотел бы начать здесь

<form action="C:\Users\Nelle\Documents\NetBeansProjects\EmployeeDB\src\java\web\HiringServlet" method="POST"> 

Есть ли у вас какие-либо подсказки о вашей HiringServlet называют?

+0

Эта строка уже была в программе, которую я дал в качестве отправной точки, за исключением того, что я изменил ее, чтобы включить полный каталог (C: \ Users и т. Д.), Потому что это давало мне ошибку без нее. До этого, если читать: action = "HiringServlet" – user2302019

Смежные вопросы