【问题标题】:Doesn't see the Spring MVC mapping java没有看到 Spring MVC 映射 java
【发布时间】:2018-02-28 01:04:18
【问题描述】:

嘿,我有一个 ajax 请求,当我按下按钮时会调用它,但是 servlet 映射不起作用。当我按下按钮时,它不会进入控制器。 这是向控制器发出 ajax 请求的脚本。

<script type="text/javascript">
     function getData() {
        var dataToBeSent = {
            uName : $("#jsonResponse").text() //
        }; 

        $.ajax({
            url : 'something/testing', // Your Servlet mapping or JSP(not suggested)
            data : dataToBeSent,
            type : 'POST',
            dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
            success : function(response) {
                $('#outputDiv').html(response); // create an empty div in your page with some id
            },
            error : function(request, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }; 


</script> 

#jsonResponse 是一个

是首先动态分配的。 这是控制器:

@Controller
@RequestMapping("/something")
public class Test {

    @RequestMapping("/testing")
    public void test(@RequestBody String yey){

    Connection conn = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/api?user=root&password=1234");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    String query = "INSERT INTO test(Id, nume) value (default, ?)";
    PreparedStatement preparedStmt;
    try {
        preparedStmt = conn.prepareStatement(query);
        preparedStmt.setString (1, yey);
        preparedStmt.execute();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    System.out.println(yey);        
}
}

【问题讨论】:

  • 你有 404 错误吗?到达服务器?是不是js控制台报错了?
  • @MohamedBathaoui 是的,我有这个错误 POST localhost:8080/ApiAi/something/testing 404 ()

标签: javascript java ajax spring-mvc controller


【解决方案1】:

我认为在您的 servlet 中,您忘记设置您的 servlet 应该侦听的 POST 或 GET 方法类型。在你的 ajax 中你发送了一个 POST 请求,但在你的 servlet 中没有提到请求的类型

@RequestMapping(value = "/something/testing", method = POST)

我认为这可能对你有用

【讨论】:

  • 我把 @RequestMapping(value = "/something/testing", method = RequestMethod.POST) 但它给了我同样的错误 POST localhost:8080/ApiAi/something/testing 404 ()跨度>
  • 所以你的服务器路由器以 ApiAI 为前缀,尝试通过 localhost:8080/something/testing 访问它,你是不是故意用 ApiAi 作为前缀?,你可以将 application.properties 的内容粘贴到 src/主要/资源?
  • 当我尝试像这样访问 localhost:8080/something/testing 时它给了我 404,因为我所有的页面都以 ApiAi 为前缀(这是项目的名称)
  • 那你为什么不在你的 ajax tcall 上指定它 o 是 url : 'ApiAi/something/testing'
  • POST localhost:8080/ApiAi/ApiAi/something/testing 500 () ajax 不去控制器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 2019-11-10
  • 2015-11-21
  • 1970-01-01
相关资源
最近更新 更多