在spring mvc中使用ajax将json对象传递给控制器​​类

时间:2017-11-19 06:42:05

标签: java json ajax spring jsp

我是初学mvc的新手并开始自己练习并且遇到以下错误。请帮助解释代码。

我将json对象从JSP页面传递给我的控制器类但得到了415错误,如不支持的媒体类型和搜索解决方案后。我包括 contentType:ajax调用中的application / json,即使那时我也找不到解决方案。

的index.jsp 我在哪里使用ajax将json对象传递给控制器​​类。

  <html>
 <body>
 <h2>Hello World!</h2>

 <input type="button" onclick="c()" value="see"/>

  <script src="js/jquery.min.js"></script>
  <script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" >
  </script>
 <script src="js/jquery.dcjqaccordion.2.7.js"></script>
   <script src="js/scripts.js"></script>
   <script src="js/jquery.nicescroll.js"></script>
   <script>

    function c(){
    alert("hi");
    var id=2;
    alert(id);
    var dc="s";
    var js={id:id,dc:dc};
    alert(js.dc);
    var res=JSON.stringify(js);
    $.ajax({ 
    "url": "http://localhost:1014/com.test/spl",
    "type": "POST",
    "ContentType" : "application/json",
    "data" : res,
    success: function(data, status) {
        if(data){
            alert("inserted ");
        }else{
        //window.open("index.jsp","_self");
            alert("not inserted");
        }
    },
     error: function(e) { 
        console.log("error");
    }  
  });  
}

</script>
</body>
</html>

DO课程

package com.mine.DO;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;

@Entity
@Table(name = "x")
public class Sample {

    public Sample() {

    }

    public Sample(int id, String dc) {
        super();
        this.id = id;
        this.dc = dc;
    }

    @Column(name = "id")
    @Id
    private int id;

    @Column(name = "dc")
    private String dc;

    public int getId() {
        return id;
    }

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

    public String getDc() {
        return dc;
    }

    public void setDc(String dc) {
        this.dc = dc;
    }
}

控制器类

package com.mine.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mine.DO.Sample;
import com.mine.service.SampleService;
import org.springframework.web.servlet.DispatcherServlet;

@Controller
public class Samplecontroller {

    @Autowired
    SampleService sampleService;

    @RequestMapping(value = "/spl",
                    method = RequestMethod.POST)
    @ResponseBody
    public void sampleInsert(@RequestBody Sample s) {

        System.out.println("in controller");
        boolean val = sampleService.add();
    }
}

SampleService接口

package com.mine.service;
import com.mine.DO.Sample;

public interface SampleService {

    public boolean add();

    public boolean add(Sample s);
}

SampleServiceImpl

package com.mine.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.mine.DO.Sample;
import com.mine.dao.Sampledao;

public class SampleServiceImpl
        implements SampleService {

    @Autowired
    Sampledao sampleDao;

    public boolean add() {
        // TODO Auto-generated method stub
        //boolean val=sampleDao.add(s);
        System.out.println("in service");
        boolean val = sampleDao.add();
        return val;
    }

    public boolean add(Sample s) {
        // TODO Auto-generated method stub
        System.out.println("in service");
        boolean val = sampleDao.add();
        return val;
    }
}

SampleDao Inteface

package com.mine.dao;
import com.mine.DO.Sample;

public interface Sampledao {

    public boolean add(Sample s);

    public boolean add();
}

SampleDaoImpl

package com.mine.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.mine.DO.Sample;

public class SampledaoImpl
        implements Sampledao {

    @Autowired
    private SessionFactory sessionFactory;

    public boolean add(Sample s) {
        //System.out.println("in impl");
        Session session = sessionFactory.getSessionFactory().openSession();
        long key = (Long) session.save(s);
        if (key > 0) {
            return true;
        }
        return false;
    }


    public boolean add() {
        System.out.println("in impl");
        return true;
    }
}

servlet.xml中

  <?xml version="1.0" encoding="UTF-8"?>

  <beans:beans xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:beans="http://www.springframework.org/schema/beans" 
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/tx 
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

  <context:component-scan base-package="com.mine"></context:component-scan>
  <beans:bean name="sampleService" 
  class="com.mine.service.SampleServiceImpl"/>  
  <beans:bean name="sampleDao" class="com.mine.dao.SampledaoImpl"/>

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


  <beans:bean id="sessionFactory" 
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">


  <beans:property name="dataSource" ref="dataSource" />
  <!-- <beans:property name="mappingResources">  
    <beans:list>  
    <beans:value>/resources/Event.hbm.xml</beans:value>
    </beans:list>  
    </beans:property> -->


          <beans:property name="hibernateProperties">
                 <beans:props>
                       <beans:prop 

     key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
                       <beans:prop 
     key="hibernate.current_session_context_class">thread</beans:prop>
                       <beans:prop 
     key="hibernate.show_sql">true</beans:prop>
                 </beans:props>
          </beans:property>
          <beans:property name="annotatedClasses">
        <beans:list>
              <beans:value>com.mine.DO.Sample</beans:value> <!-- Entity 
          classes-->


        </beans:list>
        </beans:property>
   </beans:bean>
   <beans:bean id="dataSource" 
   class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
          <beans:property name="driverClassName" 
          value="com.mysql.jdbc.Driver" />
          <beans:property name="url" 
          value="jdbc:mysql://localhost:3306/student" />
          <beans:property name="username" value="root" />
          <beans:property name="password" value="root" />
          </beans:bean>


          </beans:beans>

错误

HTTP状态415 -

输入状态报告

消息

描述服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持。

1 个答案:

答案 0 :(得分:0)

您还需要添加另一个标记Accept: application/json 与您对contentType:application/json

的处理方式相同

所以它看起来像这样

$.ajax({ 
"url": "http://localhost:1014/com.test/spl",
"type": "POST",
"ContentType" : "application/json",
"Accept": "application/json",
"data" : res,