Tomcat抛出java.lang.IndexOutOfBoundsException

时间:2019-04-20 16:36:20

标签: java maven tomcat servlets

我正在运行一个简单的Web项目。在我的一个servlet中,我从表单中获取用户的参数,并运行UserDao类的getIf方法,该方法从数据库中返回匹配某种条件的所有用户。

这是getIf代码的代码:

@Override
    public synchronized List<User> getIf(User user) {
        List<User> users = new ArrayList<>();

        users = getAll();

        int num = users.size();

        System.out.println(num);

        for (int i = 0; i < num; i++) {

            User potentialUser = users.get(i);

            boolean result = true;

            if (user.getUsername() != null && !user.getUsername().equals(potentialUser.getUsername())) {
                result = false;
            } else if (user.getPassword() != null && !user.getPassword().equals(potentialUser.getPassword())) {
                result = false;
            } else if (user.getFirstName() != null && !user.getFirstName().equals(potentialUser.getFirstName())) {
                result = false;
            } else if (user.getLastName() != null && !user.getLastName().equals(potentialUser.getLastName())) {
                result = false;
            } else if (user.getUserType() != null && !user.getUserType().equals(potentialUser.getUserType())) {
                result = false;
            } else if (user.getAge() != null && !user.getAge().equals(potentialUser.getAge())) {
                result = false;
            }

            if (!result) {
                users.remove(potentialUser);
            }

        }

        return users;
    }

每当我运行此servlet时,通过提交表单,都会收到此错误:

 java.lang.IndexOutOfBoundsException: Index: 13, Size: 12
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at com.model.databasePackage.implementations.UserDao.getIf(UserDao.java:205)
    at com.web.servlets.SearchServiceServlet.doPost(SearchServiceServlet.java:55)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

处理请求的servlet的代码如下: 包com.web.servlets;

import com.model.databasePackage.implementations.UserDao;
import com.model.objects.User;
import com.model.objects.User_Type;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchServiceServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServiceServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        response.setContentType("txt/html");

        UserDao dao = (UserDao) getServletContext().getAttribute("userDao");

        //Reading parameters
        String first_name = request.getParameter("first_name");
        String last_name = request.getParameter("last_name");
        Integer age = null;

        try {
            age = Integer.valueOf(request.getParameter("age"));
        } catch (NumberFormatException ex) {

        }

        //if the parameters is empty string,then its variable is set to null.
        first_name = first_name.equals("") ? null : first_name;
        last_name = last_name.equals("") ? null : last_name;

        User userEq = new User.UserBuilder(null, null, age, new User_Type("User"), first_name, last_name).build();

        List<User> users = dao.getIf(userEq);

        System.out.println(users.size());

        response.sendRedirect("search.html");

    }

}

我使用maven,tomcat 9和netbeans运行该项目。

1 个答案:

答案 0 :(得分:4)

请勿修改您要迭代的内容。这是一个简单的解决方案,可以跟踪要删除的用户,并在迭代完成后将其删除。

@Override
public synchronized List<User> getIf(User user) {
    List<User> users = new ArrayList<>();

    users = getAll();

    int num = users.size();

    System.out.println(num);

    List<User> toRemove = new ArrayList<>();

    for (int i = 0; i < num; i++) {

            User potentialUser = users.get(i);

            boolean result = true;

            if (user.getUsername() != null && !user.getUsername().equals(potentialUser.getUsername())) {
                result = false;
            } else if (user.getPassword() != null && !user.getPassword().equals(potentialUser.getPassword())) {
                result = false;
            } else if (user.getFirstName() != null && !user.getFirstName().equals(potentialUser.getFirstName())) {
                result = false;
            } else if (user.getLastName() != null && !user.getLastName().equals(potentialUser.getLastName())) {
                result = false;
            } else if (user.getUserType() != null && !user.getUserType().equals(potentialUser.getUserType())) {
                result = false;
            } else if (user.getAge() != null && !user.getAge().equals(potentialUser.getAge())) {
                result = false;
            }

            if (!result) {
                toRemove.add(user);
            }


        }

        toRemove.forEach(u -> users.remove(u));

        return users;
}

有一种更好的方法:

@Override
public synchronized List<User> getIf(User user) {
    List<User> users = getAll();

    return users.stream().filter(potentialUser -> {
            boolean result = true;

            if (user.getUsername() != null && !user.getUsername().equals(potentialUser.getUsername())) {
                result = false;
            } else if (user.getPassword() != null && !user.getPassword().equals(potentialUser.getPassword())) {
                result = false;
            } else if (user.getFirstName() != null && !user.getFirstName().equals(potentialUser.getFirstName())) {
                result = false;
            } else if (user.getLastName() != null && !user.getLastName().equals(potentialUser.getLastName())) {
                result = false;
            } else if (user.getUserType() != null && !user.getUserType().equals(potentialUser.getUserType())) {
                result = false;
            } else if (user.getAge() != null && !user.getAge().equals(potentialUser.getAge())) {
                result = false;
            }

            return result;
           }).collect(Collectors.toList());
}