简体   繁体   English

Ajax发布到Spring MVC控制器导致“请求的资源不可用”错误

[英]Ajax post to Spring MVC controller results in “Requested resource is unavailable” error

I have been trying to get this code to work. 我一直在尝试使此代码正常工作。 I've just started with Spring MVC (and I'm relatively new to web dev - my background is GUI dev/science) but I think the error may be triggered because there is a problem linking the jquery code in my jsp to the Spring controller. 我刚刚开始使用Spring MVC(并且我对Web开发人员相对较新-我的背景是GUI开发/科学),但我认为可能会触发该错误,因为将我的jsp中的jquery代码链接到Spring时出现问题控制器。 I've literally been trying to get this to work for days without success and I've tried all the suggestions made by posters on this forum with a similar problem - to no avail. 从字面上看,我一直试图使它成功工作数天,但我已经尝试过该论坛上的发帖人提出的所有建议,但都存在类似的问题-无济于事。 I'd therefore very much appreciate your input. 因此,非常感谢您的投入。 The project is being developed using Netbeans, Tomcat 8, Maven, Spring MVC, and Jquery. 该项目正在使用Netbeans,Tomcat 8,Maven,Spring MVC和Jquery开发。

projectDashboard.jsp (in WEB-INF/views): projectDashboard.jsp(在WEB-INF / views中):

<div class="col-lg-8 col-md-8 col-sm-8">
    <div id="projectForm">                                   
        <div class="form-group">               
            <input id="name" name="name" type="text" class="form-control" placeholder="Project name (50 characters or less)"/>
            <textarea id="description" name="description" class="form-control" placeholder="Project Description (200 characters or less)"></textarea>                                
        </div>       
        <div class="form-group">             
            <input class="btn btn-primary pull-right" id="createProjectButton" value="Create" type="button"/>                    
        </div>                       
    </div>                    
</div>                    

JQuery: jQuery的:

<script>
        $(document).ready(function(){
            $("#createProjectButton").on("click", function(){      
                var projectJson = {
                    "name":$("#name").val(),
                    "description":$("#description").val()
                };                     
                $.ajax({
                    type: "POST",
                    url: "/ProgressManagerOnline/projectDashboard",
                    data: JSON.stringify(projectJson), 
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                });                       
            });
        });            
</script>

ProjectDashboard.java (Spring MVC controller class in src/main/java): ProjectDashboard.java(src / main / java中的Spring MVC控制器类):

@RequestMapping(value = "/projectDashboard", method = RequestMethod.POST)
public String saveProject(@RequestBody Project project) throws Exception {
    return "OK";
}

Relevant code in appconfig-mvc.xml: appconfig-mvc.xml中的相关代码:

<mvc:annotation-driven/>    
<mvc:view-controller path="/" view-name="login"/> //home web page - login.jsp

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Maven pom.xml includes: Maven pom.xml包括:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.5</version>
</dependency> 
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.5</version>
</dependency>      

Tomcat context.xml: Tomcat context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ProgressManagerOnline"/>

Error in Firefox web console: Firefox Web控制台中的错误:

The requested resource is not available. (404 error)

My Project.java: 我的Project.java:

@Entity
@Table(name = "projects")
public class Project implements Serializable {

    private Long id;
    private String name;
    private String description;    
    private java.util.Date dateCreated;

    public Project(){};

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id){
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Column(name = "dateCreated", columnDefinition="DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }    
}

I've been at this for days now and have tried every suggestion posted on this forum and others. 我已经参加了好几天,并尝试了在该论坛和其他论坛上发布的所有建议。

Many thanks in advance to anyone who can help out. 在此先感谢任何可以提供帮助的人。

You are missing couple of configurations I guess in your application. 我猜您的应用程序中缺少几个配置。

You require auto conversion of json to java object , 您需要将json自动转换为java对象,

@RequestBody Project project

Hence you need to add json converter so please look documentation : http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html 因此,您需要添加json转换器,因此请查看文档: http : //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html

Add following in your configuration context xml along with required dependencies added in your pom.xml, 在配置上下文xml中添加以下内容,并在pom.xml中添加所需的依赖项,

<!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />

    <!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

(Posted on behalf of the OP) . (代表OP张贴)

The solution suggested by TechBreak worked - I was missing the Spring context dependency in my pom.xml and the extra config in my xml: TechBreak建议的解决方案有效-我在pom.xml中缺少Spring上下文依赖关系,在xml中缺少额外的配置:

<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />

<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

After a restart of the server and 重新启动服务器后,

mvn clean install

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM