Spring MVC Ajax and JQuery

When I run the programm in Eclilpse, I got the following error message:

HTTP Status 415
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

I downloaded the source code from Github and got all the jars using the author's pom.xml. I'm sure there is no problem in this area. and the programme runs ok when retrieving and deleting records from MySQL.

I google a lot,no solution. I contact the author on G+, no response yet. Finally, I run the project in Chrome instead of Eclipse-built-in browser, and Everything i ok.

[java]  view plain copy
  1. package com.mobapp.controller;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.http.MediaType;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestBody;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.mobapp.model.Smartphone;  
  17. import com.mobapp.service.SmartphoneService;  
  18.   
  19. @Controller  
  20. @RequestMapping(value="/smartphones")  
  21. public class SmartphoneController {  
  22.       
  23.     @Autowired  
  24.     private SmartphoneService smartphoneService;  
  25.       
  26.     @RequestMapping(value="/create", method=RequestMethod.GET)//xin change it to post,it was get.it sucks if changed into get  
  27.     public ModelAndView createSmartphonePage() {  
  28.         System.out.println("it does arrived into createSmartPhonePage");  
  29.         ModelAndView mav = new ModelAndView("phones/new-phone");  
  30.         mav.addObject("sPhone"new Smartphone());  
  31.         return mav;  
  32.     }  
  33.       
  34.     @RequestMapping(value="/create", method=RequestMethod.POST,   
  35.             produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)  
  36.     @ResponseBody  
  37.     public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {  
  38.         System.out.println("createSmartphone");  
  39.         return smartphoneService.create(smartphone);  
  40.     }  
  41.       
  42.     @RequestMapping(value="/edit/{id}", method=RequestMethod.GET)  
  43.     public ModelAndView editSmartphonePage(@PathVariable int id) {  
  44.         ModelAndView mav = new ModelAndView("phones/edit-phone");  
  45.         Smartphone smartphone = smartphoneService.get(id);  
  46.         mav.addObject("sPhone", smartphone);  
  47.         return mav;  
  48.     }  
  49.       
  50.     @RequestMapping(value="/edit/{id}", method=RequestMethod.PUT,   
  51.             produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)  
  52.     @ResponseBody  
  53.     public Smartphone editSmartphone(@PathVariable int id,   
  54.             @RequestBody Smartphone smartphone) {  
  55.         smartphone.setId(id);  
  56.         return smartphoneService.update(smartphone);  
  57.     }  
  58.       
  59.     @RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE,   
  60.             produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)  
  61.     @ResponseBody  
  62.     public Smartphone deleteSmartphone(@PathVariable int id) {  
  63.         return smartphoneService.delete(id);  
  64.     }  
  65.       
  66.     @RequestMapping(value="", method=RequestMethod.GET,  
  67.             produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)  
  68.     @ResponseBody  
  69.     public List<Smartphone> allPhones() {  
  70.         return smartphoneService.getAll();  
  71.     }  
  72.       
  73.     @RequestMapping(value="", method=RequestMethod.GET)  
  74.     public ModelAndView allPhonesPage() {  
  75.         ModelAndView mav = new ModelAndView("phones/all-phones");  
  76.         List<Smartphone> smartphones = new ArrayList<Smartphone>();  
  77.         smartphones.addAll(allPhones());  
  78.         mav.addObject("smartphones", smartphones);  
  79.         return mav;  
  80.     }  
  81.       
  82. }  

[java]  view plain copy
  1. package com.mobapp.init;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Locale;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.springframework.context.annotation.Bean;  
  10. import org.springframework.context.annotation.ComponentScan;  
  11. import org.springframework.context.annotation.Configuration;  
  12. import org.springframework.context.annotation.Import;  
  13. import org.springframework.context.annotation.PropertySource;  
  14. import org.springframework.core.env.Environment;  
  15. import org.springframework.http.MediaType;  
  16. import org.springframework.web.accept.ContentNegotiationManager;  
  17. import org.springframework.web.servlet.View;  
  18. import org.springframework.web.servlet.ViewResolver;  
  19. import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;  
  20. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  21. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;  
  22. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  23. import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;  
  24. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  25. import org.springframework.web.servlet.view.JstlView;  
  26. import org.springframework.web.servlet.view.json.MappingJacksonJsonView;  
  27.   
  28. @Configuration  
  29. @EnableWebMvc  
  30. @Import({DataBaseConfig.class})  
  31. @ComponentScan("com.mobapp")  
  32. @PropertySource("classpath:application.properties")  
  33. public class WebAppConfig extends WebMvcConfigurerAdapter {  
  34.       
  35.     @Resource  
  36.     private Environment env;  
  37.       
  38.     @Override  
  39.     public void addResourceHandlers(ResourceHandlerRegistry registry) {  
  40.         registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");  
  41.     }  
  42.       
  43.     @Override  
  44.     public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {  
  45.         configurer.favorPathExtension(true)  
  46.             .useJaf(false)  
  47.             .ignoreAcceptHeader(true)  
  48.             .mediaType("html", MediaType.TEXT_HTML)  
  49.             .mediaType("json", MediaType.APPLICATION_JSON)  
  50.             .defaultContentType(MediaType.TEXT_HTML);  
  51.     }  
  52.       
  53.     @Bean  
  54.     public ViewResolver contentNegotiatingViewResolver(  
  55.             ContentNegotiationManager manager) {  
  56.           
  57.         List<ViewResolver> resolvers = new ArrayList<ViewResolver>();  
  58.           
  59.         InternalResourceViewResolver r1 = new InternalResourceViewResolver();  
  60.         r1.setPrefix("/WEB-INF/pages/");  
  61.         r1.setSuffix(".jsp");  
  62.         r1.setViewClass(JstlView.class);  
  63.         resolvers.add(r1);  
  64.           
  65.         JsonViewResolver r2 = new JsonViewResolver();  
  66.         resolvers.add(r2);  
  67.           
  68.         ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();  
  69.         resolver.setViewResolvers(resolvers);  
  70.         resolver.setContentNegotiationManager(manager);  
  71.         return resolver;  
  72.           
  73.     }  
  74.       
  75.     /**  
  76.     * View resolver for returning JSON in a view-based system. Always returns a  
  77.     * {@link MappingJacksonJsonView}.  
  78.     */  
  79.     public class JsonViewResolver implements ViewResolver {  
  80.         public View resolveViewName(String viewName, Locale locale)  
  81.                 throws Exception {  
  82.                 MappingJacksonJsonView view = new MappingJacksonJsonView();  
  83.                 view.setPrettyPrint(true);  
  84.                 return view;  
  85.         }  
  86.     }  
  87.   
  88. }  
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  3.     pageEncoding="ISO-8859-1"%>  
  4.   
  5. <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>  
  6. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
  7.   
  8.   
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  10. <html xmlns="http://www.w3.org/1999/xhtml">  
  11. <head>  
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
  13. <title>Create new Smartphone</title>  
  14. <link href="../resources/css/main.css" rel="stylesheet" type="text/css"/>  
  15. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
  16. <script type="text/javascript">  
  17.      
  18.     $(document).ready(function() {  
  19.         
  20.       $('#newSmartphoneForm').submit(function(event) {  
  21.             
  22.           var producer = $('#producer').val();  
  23.           alert(producer);  
  24.           var model = $('#model').val();  
  25.           var price = $('#price').val();  
  26.           var json = { "producer" : producer, "model" : model, "price": price};  
  27.             
  28.         $.ajax({  
  29.             url: $("#newSmartphoneForm").attr( "action"),  
  30.             data: JSON.stringify(json),  
  31.             type: "POST",  
  32.             //type: "GET",  
  33.               
  34.             beforeSend: function(xhr) {  
  35.                 xhr.setRequestHeader("Accept", "application/json");  
  36.                 xhr.setRequestHeader("Content-Type", "application/json");  
  37.                 //xhr.setRequestHeader("Content-Type", "application/xml");  
  38.             },  
  39.             success: function(smartphone) {  
  40.                 var respContent = "";  
  41.                   
  42.                 respContent += "<span class='success'>Smartphone was created: [";  
  43.                 respContent += smartphone.producer + " : ";  
  44.                 respContent += smartphone.model + " : " ;  
  45.                 respContent += smartphone.price + "]</span>";  
  46.                   
  47.                 $("#sPhoneFromResponse").html(respContent);           
  48.             }  
  49.         });  
  50.            
  51.         event.preventDefault();  
  52.       });  
  53.          
  54.     });     
  55.   </script>  
  56. </head>  
  57. <body>  
  58. <div id="container">  
  59. <h1>Create new Smartphone</h1>  
  60. <div>  
  61. <p>Here you can create new Smartphone:</p>  
  62. <div id="sPhoneFromResponse"></div>  
  63. </div>  
  64. <form:form id="newSmartphoneForm" action="${pageContext.request.contextPath}/smartphones/create.json" commandName="sPhone">  
  65. <table>  
  66. <tbody>  
  67. <tr>  
  68. <td>Producer:</td>  
  69. <td>  
  70. <form:select path="producer">  
  71.     <form:option value="NOKIA">Nokia</form:option>  
  72.     <form:option selected="selected" value="IPHONE">iPhone</form:option>  
  73.     <form:option value="HTC">HTC</form:option>  
  74.     <form:option value="SAMSUNG">Samsung</form:option>  
  75. </form:select>  
  76. </td>  
  77. </tr>  
  78. <tr>  
  79. <td>Model:</td>  
  80. <td><form:input path="model" /></td>  
  81. </tr>  
  82. <tr>  
  83. <td>Price:</td>  
  84. <td><form:input path="price" /></td>  
  85. </tr>  
  86. <tr>  
  87. <td><input type="submit" value="Create" /></td>  
  88. <td></td>  
  89. </tr>  
  90. </tbody>  
  91. </table>  
  92. </form:form>  
  93. <a href="${pageContext.request.contextPath}/index.html">Home page</a>  
  94. </div>  
  95. </body>  
  96. </html>  

Sure the sweetheart only love modern browser

Spring MVC Ajax and JQuery_第1张图片

the original article:  http://www.javacodegeeks.com/2013/09/spring-mvc-ajax-jquery.html

the soruce code:http://pan.baidu.com/share/link?shareid=3929158057&uk=3878681452

你可能感兴趣的:(Spring MVC Ajax and JQuery)