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

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

游皓
2023-03-14

TLDR:如果我使用Tomcat而不是Glassfish,或者使用jkd 1.7而不是JDK1.8,我是否必须使用不同的语法来访问我的servlet?我无法让jquery ajax与servlet通信(在Eclipse1.7JDK tomcat中,而不是在Netbeans1.8JDK glassfish中)

我试图将我的项目从Netbean 1.8 JDK转换为Eclipse 1.7 JKD。

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

我认为问题是它没有将我的ajax"search"映射到servlet"/search"。

servlet被注释

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

我必须假设这适用于JDK1.7。。。。。?

我在添加一个和我的网络豆一样的玻璃鱼服务器时遇到了麻烦。我设法添加了它,但后来它消失了,我没有任何可用的服务器,直到我放弃并放入一个公猫服务器。然而,我不知道你是否应该进一步配置它。

我试图通过将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

我不得不更改我的环境变量以降级到JDK1.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

爪哇之家酒店

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

我即将放弃并恢复使用Netbeans 1.8 JDK,并将我的web项目上传到Google App Engine(仅适用于1.7)之外的其他地方。我会再给它一个小时,以防有人能帮助我,但我已经花了太长时间浪费我的时间,当有另一个选择。

就像我说的,我怀疑问题与我的服务器配置或与此相关的文件有关。下面我将粘贴我的ajax和servlet。它们都可以在NetBeans1.8JDK中工作,但可能需要为Eclipse1.7JDK进行更改?

谢谢你的阅读!

滑动分页

$(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而不是JDK1.8,我是否必须使用不同的语法来访问我的servlet?我无法让jquery ajax与servlet通信(在Eclipse1.7JDK tomcat中,而不是在Netbeans1.8JDK glassfish中)

共有1个答案

田志尚
2023-03-14

据我所知,符号

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

仅适用于JDK1.8,但如果您仍然使用JDK1.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>
 类似资料:
  • 我在同一个jvm中运行Netty客户端和服务器并试图停止服务器时遇到问题。以下是我的代码来举例说明: 我已经用Netty 3.4.0测试过了。最终和3.4.4。最后,我不知道我做错了什么。 为什么在服务器关闭后,客户端仍然可以向服务器发送数据?

  • 我有麻烦映射一个嵌套dto字段正确与MapStruct。我有几个DTO: 具有相应的映射器 到目前为止,一切工作都很好,生成的代码自动连接其他需要的映射器来正确地构建DTO。例如生成的仪器映射器实现 现在,当我试图创建一个包含嵌套工具dto的映射器时遇到了麻烦。映射器应使用instrumentMapper正确创建所需的dto。DTO: 映射器: 生成的代码: 现在media mapper得到了很好

  • 我正在使用Netbeans在我的php服务器上工作。当我尝试上传我的项目时,没有错误,但文件在服务器上保持不变。 示例:我在css中将高度从10%改为7%并上传。没有错误发生,但高度在现场保持不变。 220 ProFTPD 1.3.5服务器(Debian)[::FFFF:###.###.##.#####] 用户####### #######需要331密码 230用户#######登录 I型 200

  • 我有以下控制器 这是正确映射的: 但是当我在浏览器中输入网址时,我得到302代码,服务器立即重定向到应用程序的主页。有人能帮忙吗?为什么服务器不返回200或至少404? 亚当 @注释:这些代码的作用完全相同。 我想知道这个奇怪的重定向是否是由一些Spring配置引起的,但是在哪里检查呢?它只是项目中出现问题的地方。

  • 我有一个wcf客户端,其中要求我同时使用证书和用户名安全性。 在我输出的头签名中,存在两个引用元素。一个映射(通过URI)到UsernameToken,我的理解是另一个引用元素应该映射到SecurityTokenReference,但它不是。 请注意,这个问题实际上是我的主要问题的一个子问题,我已经在如何使WCF客户端符合特定的WS-Security-SignUsernameToken和Secur

  • 我正在使用Spring Data Neo4j3.4.x,并尝试切换到使用高级映射模式。我已经将pom.xml设置为包含必要的aspectj-maven-plugin内容,我可以看到代码编译得很好,ajc完成了它的工作。