Search code examples
javajquerymavenspring-mvctomcat8

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. 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.

projectDashboard.jsp (in 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:

<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):

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

Relevant code in 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:

<!-- 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:

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

Error in Firefox web console:

The requested resource is not available. (404 error)

My 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.


Solution

  • You are missing couple of configurations I guess in your application.

    You require auto conversion of json to java object ,

    @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

    Add following in your configuration context xml along with required dependencies added in your 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>