当前位置: 首页 > 知识库问答 >
问题:

如何在MVC中连接到java(jsp、servlet)中的不同表?

陶裕
2023-03-14

在我的java web项目中,我有四个包,即com.hrms.model、com.hrms.service、com.hrms.servlet、com.hrms.utility。在MODEL中,我有基类project、employee和training及其属性和geters和seters来检索数据。

在服务方面,我有服务实现接口,它的实现是;

package com.hrms.service;

public class EmployeeServiceImplement implements IEmployeeService 
{


/** Initialize logger */
public static final Logger log = 
Logger.getLogger(EmployeeServiceImplement.class.getName());

private static Connection connection;

private static Statement statement;

private PreparedStatement preparedStatement;

/**
 * Add set of employees for as a batch from the selected employee List
 * 
 * @throws SQLException
 *             - Thrown when database access error occurs or this method is
 *             called on a closed connection
 * @throws SAXException
 *             - Encapsulate a general SAX error or warning
 * @throws IOException
 *             - Exception produced by failed or interrupted I/O operations.
 * @throws ParserConfigurationException
 *             - Indicates a serious configuration error.
 * 
 */
@Override
public void addEmployee(Employee employee) 
{

    String employeeID = EmployeeCommonUtility.generateIDs(getEmployeeIDs());

    try 
    {
        connection = EmployeeDBConnection.getDBConnection();
        /*
         * Query is available in EmployeeQuery.xml file and use
         * insert_employee key to extract value of it
         */
 preparedStatement=connection.
prepareStatement(EmployeeQueryUtility.
queryByID(EmployeeConstants.QUERY_ID_INSERT_EMPLOYEES));
        connection.setAutoCommit(false);

        //Generate employee IDs
        employee.setEmployeeID(employeeID);
        preparedStatement.setString(EmployeeConstants.
COLUMN_INDEX_ONE, employee.getEmployeeID());
        preparedStatement.setString(EmployeeConstants.
COLUMN_INDEX_TWO, employee.getNIC());
            // Add employee
        preparedStatement.execute();
        connection.commit();

    } 
} 

    catch (SQLException | SAXException | IOException | ParserConfigurationException | ClassNotFoundException e) 
    {
        log.log(Level.SEVERE, e.getMessage());
    } 

    finally 
    {
        /*
         * Close prepared statement and database connectivity at the end of
         * transaction
         */
        try 
        {
            if (preparedStatement != null) 
            {
                preparedStatement.close();
            }

            if (connection != null) 
            {
                connection.close();
            }
        } 

        catch (SQLException e) 
        {
            log.log(Level.SEVERE, e.getMessage());
        }
    }
} 
//from this part onwards i have replased employees with project, since it's 
project section which causes the error.
@Override
public Project getProjectByID(String projectID) 
{
    return actionOnProject(projectID).get(0);
}
@Override
public ArrayList<Project> getProjects() 
{
    return actionOnProject(null);
}
private ArrayList<Project> actionOnProject(String projectID) 
{
    ArrayList<Project> projectList = new ArrayList<Project>();

    try 
    {
        connection = ProjectDBConnection.getDBConnection();
        /*
         * Before fetching project it checks whether project ID is
         * available
         */
        if (projectID != null && !projectID.isEmpty()) 
        {
            /*
             * Get project by ID query will be retrieved from
             * ProjectQuery.xml
             */
            preparedStatement = connection.prepareStatement
(ProjectQueryUtility.queryByID(ProjectConstants.QUERY_ID_GET_PROJECT));
            preparedStatement.setString
(ProjectConstants.COLUMN_INDEX_ONE, projectID);
        }
        /*
         * If project ID is not provided for get employee option it display
         * all projects
         */
        else 
        {
            preparedStatement = connection.prepareStatement
(ProjectQueryUtility.queryByID(ProjectConstants.QUERY_ID_ALL_PROJECTS));
        }

        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) 
        {
            Project project = new Project();

    project.setProjectID
(resultSet.getString(ProjectConstants.COLUMN_INDEX_ONE));

 project.setName
(resultSet.getString(ProjectConstants.COLUMN_INDEX_TWO));

    project.setStartDate
(resultSet.getString
(ProjectConstants.COLUMN_INDEX_THREE));

  project.setEndDate
(resultSet.getString(ProjectConstants.COLUMN_INDEX_FOUR));

  project.setDepartment(resultSet.getString
(ProjectConstants.COLUMN_INDEX_FIVE));
            project.setCost(Double.parseDouble
(resultSet.getString(ProjectConstants.COLUMN_INDEX_SIX)));

  project.setClientID
(resultSet.getString
(ProjectConstants.COLUMN_INDEX_SEVEN));

            projectList.add(project);
        }

    } 

    catch (SQLException | SAXException | 
IOException | ParserConfigurationException | ClassNotFoundException e) 
    {
        log.log(Level.SEVERE, e.getMessage());
    } 

    finally 
    {
        /*
         * Close prepared statement and database connectivity at the end of
         * transaction
         */
        try 
        {
            if (preparedStatement != null) 
            {
                preparedStatement.close();
            }

            if (connection != null)
            {
                connection.close();
            }
        } 

        catch (SQLException e) 
        {
            log.log(Level.SEVERE, e.getMessage());
        }
    }

    return projectList;
}
 **In Utility** I have these classes;

public class EmployeeCommonUtility 
{

/** Initialize logger */
public static final Logger log = Logger.getLogger(IEmployeeService.class.getName());

public static final Properties properties = new Properties();

static {
    try {

        // Read the property only once when load the class
        properties.load(EmployeeQueryUtility.class.getResourceAsStream(EmployeeConstants.PROPERTY_FILE));

    } 

    catch (IOException e) 
    {
        log.log(Level.SEVERE, e.getMessage());
    }
}

/**
 * Add new Employee ID
 * 
 * @param arrayList
 * @return
 */
public static String generateIDs(ArrayList<String> arrayList) 
{

    String id;
    int next = arrayList.size();
    next++;
    id = EmployeeConstants.EMPLOYEE_ID_PREFIX + next;
    if (arrayList.contains(id)) 
    {
        next++;
        id = EmployeeConstants.EMPLOYEE_ID_PREFIX + next;
    }

    return id;
}
}


public class EmployeeConstants 
{

/** Constant for config.properties key for query file path */
public static final String QUERY_XML = "queryFilePath";

/** Constant for file path of config.properties */
public static final String PROPERTY_FILE = "employee.config.properties";
.
.
.
.
}
public class EmployeeQueryUtility extends EmployeeCommonUtility 
{

/**
 * This method read the EmployeeQuery.xml file and retrieve the query by
 * query id.
 * 
 * @param id
 *            QueryID to retrieve elements
 * 
 * @return String formatted query will be returned as output
 * 
 * @throws ParserConfigurationException
 *             - Indicates a serious configuration error.
 * @throws IOException
 *             - This class is the general class of exceptions produced by
 *             failed or interrupted I/O operations.
 * @throws SAXException
 *             - Encapsulate a general SAX error or warning.
 * 
 * @see EmployeeServiceImplement#addEmployees()
 * @see EmployeeServiceImplement#createEmployeeTable()
 * @see EmployeeServiceImplement#displayAllEmployees()
 * @see EmployeeServiceImplement#removeEmployee(String)
 * 
 */
public static String queryByID(String id) throws SAXException, IOException, ParserConfigurationException 
{
    NodeList nodeList;
    Element element = null;
    /*
     * Read the EmployeeQuery.xml file and read each query node into node
     * list. It refers tag name query
     */
    nodeList = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(System.getProperty("catalina.base") + "\\wtpwebapps\\HRMS\\WEB-INF\\EmployeeQuery.xml"))
            .getElementsByTagName(EmployeeConstants.TAG_NAME);

    /*
     * Extract the node from node list using query id query id is taken from
     * query node attribute
     */

    for (int value = 0; value < nodeList.getLength(); value++) 
    {
        element = (Element) nodeList.item(value);
        if (element.getAttribute(EmployeeConstants.ATTRIB_ID).equals(id))
            break;
    }

    return element.getTextContent().trim();
}
}

package com.hrms.utility;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * This is the Database connection creation class .
 * @see #CommonUtility
 */

public class EmployeeDBConnection extends EmployeeCommonUtility 
{

private static Connection connection;

// This works according to singleton pattern
private EmployeeDBConnection() 
{
}

/**
 * Create Database connection for the given URL, Username and Password
 * 
 * @return Connection this returns SQL connection for MySql Database
 * 
 * @throws ClassNotFoundException
 *             - Thrown when an application tries to load in a class through
 *             its string name
 * @throws SQLException
 *             - An exception that provides information on a database access
 *             error or other errors
 */
public static Connection getDBConnection() throws ClassNotFoundException, SQLException 
{
    /*
     * This create new connection objects when connection is closed or it is
     * null
     */
    if (connection == null || connection.isClosed())
    {


    Class.forName(properties.getProperty(EmployeeConstants.DRIVER_NAME));
        connection = DriverManager.getConnection(properties.getProperty(EmployeeConstants.URL),
                properties.getProperty(EmployeeConstants.USERNAME), properties.getProperty(EmployeeConstants.PASSWORD));
    }

    return connection;
}
}

在getEmployee.jsp中

<%@page import="com.hrms.model.Employee"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<jsp:include page="/WEB-INF/views/header.jsp"></jsp:include>
<h2 class="h2" >Get Employee</h2>
<br>
<br>
<%
    Employee employee = (Employee) request.getAttribute("employee");
%>

<form method="POST" action="UpdateEmployeeServlet">
    <table>
        <tr>
            <td>Employee ID</td>
            <td><input type="text" name="employeeID" disabled="disabled"
                value="<%=employee.getEmployeeID()%>" /></td>
        </tr>
        <tr>
            <td>NIC</td>
            <td><input type="text" name="NIC" 
                value="<%=employee.getNIC()%>" /></td>
        </tr>
        <tr>
            <td>Employee Name</td>
            <td><input type="text" name="employeeName"
                value="<%=employee.getName()%>" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="hidden" name="employeeID" value=" 
 <%=employee.getEmployeeID()%>" /> 
                <input type="submit" value="Update Employee" class="btn btn- 
 primary"/>
            </td>
        </tr>
    </table>
</form>

<table>
    <tr>
        <td colspan="2">
            <form method="POST" action="DeleteEmployeeServlet">
                <input type="hidden" name="employeeID" value="<%=employee.getEmployeeID()%>" /> 
                <input type="submit" value="Delete  Employee" class="btn btn-primary"/>
            </form>
        </td>
    </tr>
</table>
<jsp:include page="/WEB-INF/views/footer.jsp"></jsp:include>
</body>
</html>

在listemployee.jsp中

 <%@page import="com.hrms.model.Project"%>
 <%@page import="java.util.ArrayList"%>
 <%@page import="com.hrms.service.ProjectServiceImplement"%>
 <%@page import="com.hrms.service.IProjectService"%>

 <html>
 <head>
 <!-- Bootstrap -->
 <link href="css/bootstrap.min.css" rel="stylesheet">

 </head>
 <body>
 <jsp:include page="/WEB-INF/views/header.jsp"></jsp:include>
 <br>
 <br>
 <form method="POST" action="addProject.jsp">
    <td scope="row"><input type="submit" value= "Add Project" 
 class="btn btn-primary btn-md" />  
 </form>
  <div align="left">
    <table class="table table-hover">
     <caption><h2 style="color:#800080" class="text-center">
 HumanConcepts inc. Project Database</h2></caption>
      <thead>
      <tr>
            <th scope="col">Project ID</th>
            <th scope="col">Project Name</th>
            <th scope="col">Start Date</th>
            <th scope="col">End Date</th>
            <th scope="col">Department</th>
            <th scope="col">Cost</th>
            <th scope="col">Client ID</th>
        </tr>
        <thead>
        <%
            IProjectService iProjectService = new ProjectServiceImplement();
                        ArrayList<Project> 
 arrayList = iProjectService.getProjects();

                        for(Project project : arrayList){
        %>
        <tbody>
         <tr>
            <td scope="row"> <%=project.getProjectID() %> </td>
            <td scope="row"> <%=project.getName() %> </td>
            <td scope="row"> <%=project.getStartDate() %> </td>
            <td scope="row"> <%=project.getEndDate() %> </td>
            <td scope="row"> <%=project.getDepartment() %> </td>
            <td scope="row"> <%=project.getCost() %> </td>
            <td scope="row"> <%=project.getClientID() %> </td>
            <form method="POST" action="GetProjectServlet">
            <td scope="row">
            <input type="submit" value= "Select Project" 
 class="btn btn-primary btn-xs" />  
            <input type="hidden" name="projectID" 
value="<%=project.getProjectID()%>"/>
             </form>
             </td>  
            </tr>
        <tbody>         
        <%  
           }
        %>     
    </table>
    </div>
    <jsp:include page="/WEB-INF/views/footer.jsp"></jsp:include>
</body>
</html>

对于每个员工、项目和培训,我有相同格式的代码段。

jasperException:处理[WEB-INF/views/listprojects.jsp]行[56]53:54:<%55:IProjectService IProjectService=new ProjectServiceImplement()时发生异常;56:ArrayList ArrayList=IProjectService.getProjects();57:
58:for(Project Project:arrayList){59:%>

因为很难把所有的代码段都放在这里,如果您需要澄清我代码中的任何地方,请随意让我把它放进去。我认为,当两次在同一个数据库中建立两个新连接时,会导致此错误。但我不知道如何通过保留MVC在不同的表中导航。

有什么克服这个错误的建议吗?谢谢!

StackTrace:]根原因java.lang.noClassDefFounderRor:无法在com.hrms.service.projectServiceImplement.ActionOnProject(ProjectServiceImplement.java:242)在com.hrms.service.projectServiceImplement.getProjectServiceImplement.java:137)在org.apache.jsp.web_002dinf.views.listProject_jsp._jspService(ListProject_jsp.jsp:186)在.http.httpservlet.service(httpservlet.java:741)在org.apache.jasper.servlet.jspservlet.serviceJSPSPFile(jspservlet.java:444)在org.apache.jasper.servlet.jspservlet.serviceJSPSPFile(jspservlet.java:386)在org.apache.jasper.jspservlet.service(jspservlet.java:330)在javax.servlet.http.httpservlet.service(httpservlet.java:741)在ina.core.applicationFilterChain.doFilter(ApplicationFIlterChain.java:166)在org.apache.tomcat.websocket.server.wsfilter.doFilter(wsfilter.java:53)在org.apache.catalina.core.applicationFilterChain.InternaldoFilter(applicationFilterChain.java:193)在org.apache.catalina.core.applicationFilterChain.doFilter(applicationFilterChain.java:166)在org.apache.catalina.core.applicationDispatcher.invoke.applicationDispatcher.doForward(applicationDispatcher.java:384)在org.apache.catalina.core.applicationDispatcher.forward(applicationDispatcher.java:312)在com.hrms.servlet.listprojectServlet.doPost(listprojectServlet.java:47)在javax.servlet.http.httpservlet.service(httpservlet.java:660)在javax.servlet.http.httpservlet.service(httpservlet.java:741)在IlterChain.doFilter(applicationFilterChain.java:166)在org.apache.tomcat.websocket.server.wsfilter.doFilter(wsfilter.java:53)在org.apache.catalina.core.applicationFilterChain.internaldoFilter(applicationFilterChain.java:193)在org.apache.catalina.core.applicationFilterChain.java:193)在org.apache.catalina.core.applicationFilterChain.doFilter valve.java:96)在org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase.invoke(authenticatorbase.java:494)在org.apache.catalina.core.standardhostvalve.invoke(standardhostvalve.invoke(standardhostvalve.java:137)在org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve.invoke(服务(coyoteadapter.java:343)在org.apache.coyote.http11.http11processor.service(http11processor.java:407)在org.apache.coyote.abstractProcessorlight.process(abstractProcessorlight.java:66)在org.apache.coyote.abstractProtocol.process(abstractProtocol.java:754)在org.apache.tomcat.util.net.nioEndpoint$socketProcessor.dorun(nioEndpoint.java:1376)在a.util.concurrent.ThreadPoolExecutor$worker.run(未知来源)位于org.apache.tomcat.util.threads.taskthread$wrappingrunnable.run(taskthread.java:61)位于java.lang.thread.run(未知来源)

共有1个答案

章昱
2023-03-14

问题似乎是在类路径上找不到类com.hrms.utility.projectDBConnection(根原因java.lang.NoClassDefFounderRor)。

在调用jsp文件第56行调用的IProjectService.getProjects()时,将使用此类。

此方法调用ActionOnProject(null),然后调用Connection=projectdbConnection.getdbConnection()

如果存在,请确保在运行时类路径上找到它。

 类似资料:
  • 我无法运行我的程序。它应该将信息从JSP页面获取到servlet,这样就可以通过java类中的方法进行验证。然后,经过验证后,servlet确定是将消息发送到上一个JSP页面还是发送到成功的JSP页面。当我运行这个程序时,它会把我带到注册器。jsp页面。我输入信息,然后点击提交。它把我拖到了404找不到的页面。该链接说它正在尝试将我指向CreateUser。JavaServlet。它不应该那样做。

  • 问题内容: 我有一个看起来像这样的servlet: 使用web.xml映射,例如: 它确实提供了我所期望的…如果我访问,它将显示“ / foo”。但是,如果我将servlet更改为转发到JSP文件: 然后,当我检查的值时,它现在报告“ whatever.jsp”而不是“ foo”。 为什么在将其转发给JSP之前进行了更改? 如何检测用户正在寻找的URL? 编辑:以防万一,这是在Google App

  • 我研究一个简单的问题已经有相当长的时间了。在包括这个网站在内的许多论坛上搜索了很多,但仍然无法解决这个问题。因此请求您的帮助。 我有一个带有文本区域和提交按钮的JSP页面。 在Servlet类中,我执行以下操作- 因此,在我点击提交按钮后,我的请求将转到servlet,并从servlet返回到原始的jsp,但我无法用servlet输出填充文本区域。我已经尝试了很多方法,就像我在互联网上发现的那样,

  • 我正在使用Eclipse创建一个Spring MVC web应用程序开发项目。我的目录结构如下所示- SRC ----类 ----Spring ----AppServlet -----servlet-context.xml -----root-context.xml ----视图 -----home.jsp ----web.xml -测试 -servlet-context.xml 请帮助说明为什么

  • 问题内容: 我正在创建一个laravel程序包,在这个页面中我需要在Redis中保存一些数据,但是我希望该程序包使用不同的Redis连接,以便他们可以在程序包的配置文件中设置Redis详细信息凭据并将其用于这个包。我想给包用户使用不同的Redis连接的自由。 如果您有任何想法,我怎么能做到这一点。任何帮助,将不胜感激。 问题答案: 文档中有一节称为 使用多个Redis连接 更改连接呼叫 您可以在运