Spring MVC Post Form提交AJAX jQuery。 415不支持的媒体类型

时间:2015-12-14 06:59:04

标签: ajax spring-mvc

我试着按照这个教程,但我不能让它在我的项目上工作:

Spring MVC Post Form Submit AJAX jQuery

这是我的整个jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="spring"uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/li/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link>
        <link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
        <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />       

        <title>cineUdeA</title>

        <script src="http:////code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">

            $(document).ready(function () {         

                $('#formulario').submit(function (e) {   

                    var frm = $('#formulario'); 
					var data = {};
                    var Form = this;
                    
                    $.each(this, function (i, v) {
                        var input = $(v);
                        data[input.attr("name")] = input.val();
                        delete data["undefined"];
                    });
                    $.ajax({
                        
                        contentType: 'application/json',
                        type: frm.attr('method'), 
                        url: frm.attr('action'), 
                        dataType: 'json', 
                        data: JSON.stringify(data), 

                        success: function (programacion) {           
                            alert("Response: id: " + programacion.idProgramacion + "Sala: " + programacion.sala + "  Pelicula: " + programacion.pelicula + "  hora: " + programacion.hora);
                            $(this).html("Success!");
                        },
                        error: function () {
                            $(this).html("Error!");
                        }
                    });
                });
            });
        </script>

    </head>
    <body>

    <form:form   commandName="programacion" method="post" action="insertarProgramacion"  id="formulario" >

        <fieldset>
            <legend>Detalles de programacion</legend>
            <ol>
                <font color="black">
                    <%--<form:hidden path="idProgramacion"/>--%> 
                    <li>                
                        <p><label for=idProgramacion>id:</label>       
                            <form:input path="idProgramacion"  type="text" required="true"/></p>
                    </li>

                    <li>
                        <p><label for=sala>Sala:</label>       
                            <form:input path="sala"  type="text" required="true"/></p>
                    </li>

                    <li>
                        <p><label for=pelicula>Pelicula:</label>       
                            <form:input path="pelicula" type="text" required="true"/></p>

                    </li>
                    <li>
                        <p><label for=hora>Hora:</label>                              
                            <form:input path="hora" type="text" required="true"/></p>

                    </li>
                </font>
            </ol>
        </fieldset>                    
        <fieldset>
            <button id="submitId" type="submit" class="btn btn-default">Guardar</button>
        </fieldset>
       
    </form:form>
</body>

</html>

这是我控制器的一些部分

@Controller
public class ControladorFuncionario {
    
    @Autowired
    @Qualifier("programacionBean")
    private ProgramacionDAO ProgramacionDAO;

    @Autowired
    @Qualifier("usuarioBean")
    private UsuarioDAO UsuarioDAO;

@RequestMapping (value = {"/funcionario/gestionar_cartelera/nuevaProgramacion"} , method = RequestMethod.GET)
    public ModelAndView nuevaProgramacion(@ModelAttribute("programacion") Programacion programacion, ModelAndView model){
        
        Programacion nuevaProgramacion = new Programacion();
        model.addObject("programacion", nuevaProgramacion);
        
        model.setViewName("insertarProgramacion");                     
		model.setViewName("formulario_Programacion");
            
        return model;
    }
    
    
    @RequestMapping(value = {"/funcionario/gestionar_cartelera/insertarProgramacion"}, method = RequestMethod.POST) 
    @ResponseBody
    public Programacion informacionIngresada(@RequestBody Programacion programacion) {
        
        ProgramacionDAO.insertar_actualizar(programacion);
        return programacion;
        // new ModelAndView(redirect:/funcionario/gestionar_cartelera);
    }

这是我的依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.websystique.springsecurity</groupId>
    <artifactId>cineUdeA</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>
    <url>http://maven.apache.org</url>

    <name>cineUdeA</name>

    <properties>
        <springframework.version>4.1.6.RELEASE</springframework.version>
        <springsecurity.version>4.0.1.RELEASE</springsecurity.version>
        <jackson.version>1.9.10</jackson.version>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${springsecurity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${springsecurity.version}</version>
        </dependency>
        
        <!--javax servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
                
        <!--jdbc-->      
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.0.RELEASE</version>
            <type>jar</type>
        </dependency>
        
        <!-- ajax -->

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1.1</version>
        </dependency>
        
                        
        <!-- json -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        

    </dependencies>
 
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>SpringSecurityCusotmLoginFormAnnotationExample</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>SpringSecurityCusotmLoginFormAnnotationExample</finalName>
    </build>
</project>

每当我尝试添加新计划(Programacion)时,我都会获得415 Unsupported媒体类型。我想我也试过这篇文章的所有内容:

415 Unsupported Media Type

最后,这是我的DTO:

package com.websystique.springsecurity.model;

public class Programacion {

    private String idProgramacion;
    private String sala;
    private String pelicula;
    private String hora;

  

    public Programacion(String idProgramacion, String sala, String pelicula, String hora) {

        super();
        this.idProgramacion = idProgramacion;
        this.sala = sala;
        this.pelicula = pelicula;
        this.hora = hora;
    }

    public Programacion() {

    }
    
    public String getHora() {
        return hora;
    }

    public void setHora(String hora) {
        this.hora = hora;
    }

    public String getIdProgramacion() {
        return idProgramacion;
    }

    public void setIdProgramacion(String idProgramacion) {
        this.idProgramacion = idProgramacion;
    }

    public String getSala() {
        return sala;
    }

    public void setSala(String sala) {
        this.sala = sala;
    }

    public String getPelicula() {
        return pelicula;
    }

    public void setPelicula(String pelicula) {
        this.pelicula = pelicula;
    }

}

Plz,我需要一些帮助!

1 个答案:

答案 0 :(得分:0)

这是因为您提交的是表单,而不是通过package com.example.imajid.grid2.activities; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.example.imajid.grid2.R; import com.example.imajid.grid2.adapters.PagerAdapter; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //----------------------- set toolbar Toolbar iToolbar = (Toolbar) findViewById(R.id.xmlToolbar); setSupportActionBar(iToolbar); //------------------------------ initialize toolbar ActionBar actionBar = getSupportActionBar(); actionBar.setHomeAsUpIndicator(R.drawable.menu); actionBar.setDisplayHomeAsUpEnabled(true); //**************************** find tablayout *****************************// TabLayout iTabLayout = (TabLayout) findViewById(R.id.xmlTabLayout); iTabLayout.addTab(iTabLayout.newTab()); iTabLayout.addTab(iTabLayout.newTab()); iTabLayout.addTab(iTabLayout.newTab()); iTabLayout.setTabGravity(TabLayout.GRAVITY_FILL); //******************************* Array list for sending titles *********************************// ArrayList<String> viewPagersTitle = new ArrayList<String>(); viewPagersTitle.add("صفحه اصلی"); viewPagersTitle.add("فیلم"); viewPagersTitle.add("آهنگ"); //******************************* find view pager in xml *****************************// ViewPager iViewPager = (ViewPager) findViewById(R.id.xmlViewPager); //************************************** Rtlizer view pager ************************************ //************************************** find adapter for view pager *******************************// PagerAdapter viewPagerAdapter = new PagerAdapter(getSupportFragmentManager() , iTabLayout.getTabCount() , viewPagersTitle); //************************************ set adapter for view pager *******************************// iViewPager.setAdapter(viewPagerAdapter); iViewPager.setCurrentItem(viewPagerAdapter.getCount()); //*********************************** setup tablayout to view pager********************************// iTabLayout.setupWithViewPager(iViewPager); mDrawerLayout = (DrawerLayout) findViewById(R.id.xmlDrawerLayoutRoot); //-------------------------------------- find navigation view NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { menuItem.setChecked(true); mDrawerLayout.closeDrawers(); Toast.makeText(MainActivity.this , menuItem.getTitle() , Toast.LENGTH_SHORT).show(); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } //onoptionItemSelected @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); String btnName = null; switch (itemId){ case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; case R.id.menu_setting: btnName = "Setting"; break; case R.id.menu_compass: btnName = "Compass"; break; case R.id.menu_help: btnName = "Help"; break; } Toast.makeText(MainActivity.this , "You clicked at " + btnName , Toast.LENGTH_SHORT).show(); return true; } } 自行处理发布请求。添加$.ajax以防止表单被提交。

e.preventDefault()