Springmvc+json building restful style-based applications

Source: Internet
Author: User
Tags uikit

One, spring version: Spring-framework-3.2.7.release

Second, the required other jar package:



Three, the main code:

<?xml version= "1.0"  encoding= "UTF-8"? ><web-app xmlns= "http://java.sun.com/xml/ns/ Java ee " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.com/xml/ Ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 "><context-param>< param-name>log4jconfiglocation</param-name><param-value>classpath:log4j.properties</ param-value></context-param><context-param><param-name>log4jrefreshinterval</ param-name><param-value>60000</param-value></context-param><context-param>< param-name>contextconfiglocation</param-name><param-value>classpath:applicationcontext.xml</ param-value></context-param><!--  Encoding and filtration  --><filter><filter-name> Encodingfilter</filter-name><filter-class>org.springframework.web.filter.characterencodingfilter </filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param ><param-name>forceencoding</param-name><param-value>true</param-value></ init-param></filter><filter-mapping><filter-name>encodingfilter</filter-name>< url-pattern>/*</url-pattern></filter-mapping><!-- spring Monitor  --><listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class></ listener><!-- Spring MVC DispatcherServlet --><servlet><servlet-name> springmvc3</servlet-name><servlet-class>org.springframework.web.servlet.dispatcherservlet</ Servlet-class><init-param><param-name>contextconfiglocation</param-name><param-value >classpath:springmvc-servlet.xml</param-value></init-param><load-on-startup>1</ Load-on-startup></servlet><servlet-mapping><servlet-name>springmvc3</servlet-name><url-pattern>/</url-pattern>< /servlet-mapping><!--  Resolve Http put request Spring cannot get the request parameter Problem  --><filter><filter-name >HiddenHttpMethodFilter</filter-name><filter-class> Org.springframework.web.filter.hiddenhttpmethodfilter</filter-class></filter><filter-mapping ><filter-name>hiddenhttpmethodfilter</filter-name><servlet-name>springmvc3</ Servlet-name></filter-mapping><display-name>uikittest</display-name><welcome-file-list ><welcome-file>/WEB-INF/jsp/index.jsp</welcome-file></welcome-file-list></web-app>


spring Mvc-servlet.xml

<?xml version= "1.0"  encoding= "UTF-8"? ><beans default-lazy-init= "true" xmlns= "/HTTP/ Www.springframework.org/schema/beans " xmlns:p=" http://www.springframework.org/schema/p "xmlns:tx="/HTTP/ Www.springframework.org/schema/tx " xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:xsi=" http:/ /www.w3.org/2001/xmlschema-instance " xmlns:context=" Http://www.springframework.org/schema/context "xmlns: Mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "        http://www.springframework.org/schema/beans        http:// www.springframework.org/schema/beans/spring-beans-3.1.xsd          http://www.springframework.org/schema/mvc        http:// www.springframework.org/schema/mvc/spring-mvc-3.1.xsd           http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/ Spring-context-3.1.xsd "><!--  Note driver  --><mvc:annotation-driven /><!--  Scan Package  --><context:component-scan base-package= "Com.citic.test.action"  /><!--  for page jumps , depending on the request to jump to different pages, such as request index.do jump to/web-inf/jsp/index.jsp --><bean id= "findjsp" class= " Org.springframework.web.servlet.mvc.UrlFilenameViewController " /><bean class=" Org.springframework.web.servlet.handler.SimpleUrlHandlerMapping "><property name=" mappings ">< props><prop key= "Index.do" >findJsp</prop><!--  represents index.do steering index.jsp page  --> <prop key= "First.do" >findJsp</prop><!--  show first.do to first.jsp page  --></props ></property></bean><!--  View Resolution  --><bean class= " Org.springframework.web.servlet.view.UrlBasedViewResolver "><!--  backThe view model data needs to be JSTL to process  --><property name= "Viewclass" value= " Org.springframework.web.servlet.view.JstlView " /><property name=" prefix " value="/web-inf/ jsp/" /><property name=" suffix " value=". jsp " /></bean><!--  Access to static resource files   do not support access to Web-inf directory  --><mvc:default-servlet-handler /><!--  access to static resource files   Support access to Web-inf directory  --><!-- <mvc:resources location= "/UIKIT-2.3.1/"  mapping= "/ uikit-2.3.1/** " /> --><bean id=" Stringconverter " class=" Org.springframework.http.converter.StringHttpMessageConverter "><property name=" Supportedmediatypes " ><list><value>text/plain;charset=UTF-8</value></list></property></bean> <!--  Output Object goto JSON supports  --><bean id= "Jsonconverter" class= " Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter "></bean><beanclass=" Org.springframewOrk.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "><property name=" Messageconverters " ><list><ref bean= "Stringconverter"/><ref bean= "Jsonconverter"  /></list ></property></bean></beans>


Contro Ller:

package com.citic.test.action;import java.util.arraylist;import java.util.list;import  net.sf.json.jsonobject;import org.apache.log4j.logger;import  org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.requestmethod;import  org.springframework.web.bind.annotation.requestparam;import  org.springframework.web.bind.annotation.responsebody;import com.citic.test.entity.person;/** *  Based on RESTful style architecture test  *  *  @author  dekota *  @since  jdk1.5 * @ version v1.0 *  @history  2014-2-15  pm 3:00:12 dekota  New  */@ controllerpublic class dekotaaction {/**  Log Instances  */private static final  Logger logger = logger.getlogger (Dekotaaction.class); @RequestMapping (value =  "/hello", produces =  "Text/plain;charset=utf-8") public @ Responsebodystring hello ()  {return  "Hello!" Hello ";} @RequestMapping (value =  "/say/{msg}", produces =  "Application/json;charset=utf-8") public  @ResponseBodyString  say (@PathVariable (value =  "msg")  string msg)  { return  "{\" msg\ ": \" You say: ' " + msg + " \ "}";} @RequestMapping (value =  "/person/{id:\\d+}",  method = requestmethod.get) public @ Responsebodyperson getperson (@PathVariable ("id")  int id)  {logger.info ("Get people information id="  + &NBSP;ID); Person person = new person ();p erson.setname ("Zhang San");p erson.setsex ("male");p Erson.setage (30); Person.setid (ID); Return person;} @RequestMapping (value =  "/person/{id:\\d+}",  method = requestmethod.delete) public   @ResponseBodyObject  deleteperson (@PathVariable ("id")  int&nbsP;id)  {logger.info ("Remove personnel information id="  + id); Jsonobject jsonobject = new jsonobject (); Jsonobject.put ("msg",  "Removal of personnel information succeeded"); return  jsonobject;} @RequestMapping (value =  "/person",  method = requestmethod.post) public @ Responsebodyobject addperson (Person person)  {logger.info ("Registered personnel information Success Id="  + person.getid ()); Jsonobject jsonobject = new jsonobject (); Jsonobject.put ("MSG",  "Registered personnel Information succeeded"); return  jsonobject;} @RequestMapping (value =  "/person",  method = requestmethod.put) public @ Responsebodyobject updateperson (Person person)  {logger.info ("Update staff information id="  +  Person.getid ()); Jsonobject jsonobject = new jsonobject (); Jsonobject.put ("MSG",  "Update personnel information succeeded"); return  jsonobject;} @RequestMapping (value =  "/person",  method = requestmethod.patch) public @ Responsebodylist<person> listpersOn (@RequestParam (value =  "name", required = false, defaultvalue =  "")  string name)  {logger.info ("Query staff name like "  + name); List<person> lstpersons = new arraylist<person> (); Person person = new person ();p erson.setname ("Zhang San");p erson.setsex ("male");p Erson.setage (25); Person.setid (101); Lstpersons.add (person); Person person2 = new person ();p erson2.setname ("John Doe");p erson2.setsex ("female");p Erson2.setage (23) ;p Erson2.setid (102); Lstpersons.add (Person2); Person person3 = new person ();p erson3.setname ("Harry");p Erson3.setsex ("male");p Erson3.setage (27) ;p Erson3.setid (103); Lstpersons.add (Person3); return lstpersons;}


index.jsp

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><%string  path = request.getcontextpath (); String basepath = request.getscheme ()  +  "://" + request.getservername ()  +   ":"  + request.getserverport () + path +  "/";%><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" > 



Partial Debug Effect:




Springmvc+json building restful style-based applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.