Tomcat抛出java.lang.IndexOutOfBoundsException

问题描述 投票:1回答:1

我正在运行一个简单的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代码如下:package 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来运行这个项目。

java maven tomcat servlets
1个回答
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());
}
© www.soinside.com 2019 - 2024. All rights reserved.