当切换到java 1.7和eclipse时,服务器没有正确地将Ajax映射到Servlet

时间:2015-04-20 12:57:53

标签: java ajax eclipse servlets netbeans

TLDR:如果我使用Tomcat而不是Glassfish或jkd 1.7而不是jdk 1.8,我是否必须使用不同的语法来访问我的servlet?我不能让我的jquery ajax与我的servlet通信(在eclipse 1.7 jdk tomcat而不是netbeans 1.8 jdk glassfish)

我正在尝试将我的项目从Netbeans 1.8 JDK转换为Eclipse 1.7 JKD。

它在Netbeans中运行良好。我花了5个多小时试图让它在Eclipse上运行。

我认为问题在于它没有映射我的ajax"搜索"到servlet" / search" 。

servlet有注释

@WebServlet(name = "SearchServlet", urlPatterns = {"/search"})

我必须假设这适用于JDK 1.7 .....?

我添加一个像我的netbeans一样的glassfish服务器时遇到了麻烦。我设法添加它然后它消失了,我没有任何服务器可用,直到我放弃并放入一个tomcat。但是我不知道你是否应该进一步配置它。

我尝试通过将glassfish服务器工具拖到我的IDE中来添加它,但它说无需更新:无需更新。所以我只是坚持使用tomcat。

这是我运行jsp时的日志:

Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:animelist1' did not find a matching property.
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Mar 23 2015 14:11:21 UTC
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.21.0
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 7
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.7.0_79\jre
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.7.0_79-b15
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\apache-tomcat-8.0.21\endorsed
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_79\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin;.
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 772 ms
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.21
Apr 20, 2015 1:48:49 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:49 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1162 ms

当我尝试通过点击jsp上的按钮进行搜索时,这是日志:

Apr 20, 2015 1:50:11 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet SearchServlet as unavailable
Apr 20, 2015 1:50:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet SearchServlet
javax.naming.NameNotFoundException: Name [main.SearchServlet/annj] is not bound in this Context. Unable to find [main.SearchServlet].
    at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
    at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:573)
    at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:461)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:144)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:121)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:817)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

在第一次进行后进一步搜索:

POST http://localhost:8080/animelist1/search 404 (Not Found)jQuery.ajaxTransport.send @ jquery-1.10.2.js:8706jQuery.extend.ajax @ jquery-1.10.2.js:8136(anonymous function) @ basic.js:8jQuery.event.dispatch @ jquery-1.10.2.js:5095jQuery.event.add.elemData.handle @ jquery-1.10.2.js:4766

我不得不将环境变量更改为降级到JDK 1.7。我把它们放在下面,因为它们是不正确的并且引起了问题(一直在乱搞它们但我认为它们现在是正确的):

(没有添加/更改用户变量)

系统变量:

路径

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin

JAVA_HOME

C:\Program Files\Java\jdk1.7.0_79

我即将放弃并恢复Netbeans 1.8 JDK并将我的网络项目上传到Google App Engine以外的其他地方(仅适用于1.7)。我会再给它一个小时,任何人都可以帮助我但是我花了很长时间浪费我的时间还有其他选择。

就像我说的,我怀疑问题与我的服务器配置或与之相关的一些文件有关。下面我将粘贴我的ajax和我的servlet。他们都在netbeans 1.8 jdk工作但也许他们需要改变eclipse 1.7 jdk?

谢谢你的阅读!

Jquery的

$(document).ready(function () {
    $('#searchForm').submit(function () {

        $.ajax({
            url: 'search',
            type: 'POST',
            dataType: 'text',
            data: $('#searchForm').serialize(),
            success: function (data) {

                $('#displaySearchResults').html(data);
//                    $('#displaySearchResults').slideDown(500);
//                
                $("#sortable1").empty();

                $.each(JSON.parse(data), function (listID, mapData) {

                    $("#sortable1").append(
                            "<li class=userList><div class=selectedItemId id=" + mapData.id + "><img class=selectedItemImg src=" 
                            + mapData.url + " alt=" + mapData.name 
                            + " style='width:216px;height:300px'></img><div id='animeTitle'>"
                            + mapData.name+ "</div></div></li>");


//                    <ul id="sortable1" class="connectedSortable">
//            <li class="ui-state-default">Item 1</li>

//                    var d1 = mapData.id;
//                    var d2 = d1.replace("'","");
//                    var div = document.createElement(d2);
//                    document.body.appendChild(div);


//                    $("#"+divName).text(mapData.id);
//                    $("#displaySearchResults2").text(mapData.name);
//                    $("#displaySearchResults3").text(mapData.url);

                });
            }
        });
        return false;
    });
});

的Servlet

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.gson.Gson;
import entities.Anime;
import entities.Ann;
import entities.Info;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author J
 */
@WebServlet(name = "SearchServlet", urlPatterns = {"/search"})
public class SearchServlet extends HttpServlet {

        /**
     * 
     */
    private static final long serialVersionUID = 1L;

        @EJB
    private AnnJAXB annj;

//    @EJB
//    private AnnJAXB annJAXB = new AnnJAXB();

    @EJB
    private Ann ann;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SearchServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SearchServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//        processRequest(request, response);

//        Map <String, Object> map = new HashMap<String, Object>();

        String searchQuery = request.getParameter("searchQuery");
//         response.getWriter().write(searchQuery);

//        map.put("searchQuery", searchQuery);
//        returnResults(response, map);

        returnResults(response, searchQuery);

    }

    private void returnResults(HttpServletResponse response, String searchQuery) throws IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        ArrayList<Map> arrayOfMap = new ArrayList<Map>();

        try {
            for (Anime anime : annj.Unmarshalling(searchQuery).getAnn()) {

                Map<String, String> map = new HashMap<String, String>();

                map.put("name", anime.getName());
                map.put("id", anime.getId());

                for (Info temp : anime.getAnime()) {
                    if (temp.getSrc() != null) {

                        map.put("url", temp.getSrc());
                    }
                }
                arrayOfMap.add(map);


            }

              response.getWriter().write(new Gson().toJson(arrayOfMap));

        } catch (Exception e) {}
    }


    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

TLDR:如果我使用Tomcat而不是Glassfish或jkd 1.7而不是jdk 1.8,我是否必须使用不同的语法来访问我的servlet?我不能让我的jquery ajax与我的servlet通信(在eclipse 1.7 jdk tomcat而不是netbeans 1.8 jdk glassfish)

1 个答案:

答案 0 :(得分:0)

据我所知,符号

  

@WebServlet(name =“SearchServlet”,urlPatterns = {“/ search”})

仅适用于jdk 1.8 但如果您仍然使用jdk 1.7,请忘记该表示法并使用此地图填充web.xml

<servlet>
    <servlet-name>search</servlet-name>
    <servlet-class>yourPackage.search</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>search</servlet-name>
    <url-pattern>/search</url-pattern>
</servlet-mapping>