Some cases of Spring MVC annotation, springmvc Annotation

Source: Internet
Author: User

Some cases of Spring MVC annotation, springmvc Annotation

1.Spring MVC-annotation (annotation) configuration file ApplicationContext. xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:tx="http://www.springframework.org/schema/tx"      xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">     <context:component-scan base-package="cn.happy.*"></context:component-scan>     </beans>

 

01. Automatic Assembly of scattered parameters in the most basic annotations of spring MVC

 

@ Controller @ RequestMapping ("/hr") public class MyController {@ RequestMapping ("/hello. do ") public String show (String name, Model model) {System. out. println ("=" + name + "="); model. addAttribute ("msg", name + ""); return "happy ";}}

InParametersAnd interface formNameAttributes and fields in the object className persistence ("three in one"). The Model type replaces the ModelAndView usage to load data and then directly return to the jsp interface,

If the graph returns happy, you need to add a view parser in the configuration file.

<! -- View parser --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "> <property name =" prefix "value ="/WEB-INF/jsp/"> </property> <property name =" suffix "value = ". jsp "> </property> </bean>

 

If the properties on the interface are inconsistent, You need to specify the @ RequestParam annotation.

@RequestMapping(value="/list.do",method=RequestMethod.POST)    public String list(Model model,@RequestParam(value="uname",required=false) String name){        System.out.println("=="+name);        return "happy";    }

 

02. Parameters of spring MVC annotation use objects, scopes, maps, and generics as Data Transmission

 

// Assembly object type @ RequestMapping (value = "/list. do ", method = RequestMethod. POST) public String list (Model model, UserInfo info) {System. out. println ("=" + info. getUname () + "\ t address" + info. getRadd (). getAdd () + "\ t Book 1" + info. getBooklist (). get (0 ). getBookname (); model. addAttribute ("uname", info. getUname (); return "index ";}

 

 

03. Get the attribute parameter value in the request's Address Bar

@ Controllerpublic class HandleReturn {/** get the attribute value in the address bar */@ RequestMapping ("/{rname}/{age}/first. do ") public String handlereturn (Model model, @ PathVariable (" rname ") String name, @ PathVariable int age) {System. out. println (name + "=" + age); model. addAttribute ("name", name); model. addAttribute ("age", age); return "handle ";}}

 

If the attribute name in the address bar is inconsistent with the method parameter name, you can use the annotation shown in the code.@ PathVariable: Specifies the relationship between attribute names rname and name in the address bar.

04.Spring MVC AnnotationReturn Value: void, Object, string

 

@ Controllerpublic class HandleAjax {@ RequestMapping ("/Ajax. do") Public void handleAjax (HttpServletResponse response) throws Exception {// Virtualize some Data Map <String, UserInfo> map = new HashMap <String, UserInfo> (); userInfo u1 = new UserInfo (); u1.setAge (12); u1.setName (""); UserInfo u2 = new UserInfo (); u2.setAge (122 ); u2.setName ("successful employment"); map. put ("001", u1); map. put ("001", u2); // tool map ---- json String fastjson String jsonString = JSON. toJSONString (map); response. setCharacterEncoding ("UTF-8"); // response stream response. getWriter (). write (jsonString); response. getWriter (). close ();}}

 

 

 

/** The Object return value type replaces other types */@ Controllerpublic class HandleAjaxObject {@ RequestMapping ("/num. do ") @ ResponseBody public Object number () {return 1 ;}@ RequestMapping (value ="/Nums. do", Produces =" text/html; charset = UTF-8 ") @ ResponseBody public Object numberS () {return" ";} // processor method ----- UserInfo @ RequestMapping (value = "/third. do ") @ ResponseBody public Object doThird () {UserInfo info = new UserInfo (); info. setAge (12); info. setName ("Happy"); return info ;}

 

Annotation @ ResponseBody is required to return data to the jsp interface when using Object as return value.

---- Js <script type = "text/javascript"> $ (function () {$ ("# btn"). click (function () {.. ajax ({url :"Nums. do", Success: function (data) {// data indicates the data that is printed from the server to the browser. alert (data )}});});}); </script> ----- body <input type = "button" id = "btn" value = "Ajax"/>

 

 

Return json data with the return value of void to the jsp Interface

<Script type = "text/javascript"> $ (function () {$ ("# btn "). click (function () {$. ajax ({url: "ajax. do ", success: function (data) {// data refers to the data printed from the server to the browser // jsonString jsonObject // {" 001 ": {" age ": 122, "name": "successful employment"} var result = eval ("(" + data + ")"); $. each (result, function (I, dom) {alert (dom. age)}) ;}}) ;}); </script> <input type = "button" id = "btn" value = "Ajax"/>

 

Finally, it is of the String type, but it is similar to the return value of the void type.

Annotation @ ResponseBody is needed to use String as return value to support json data back to jsp Interface

/** The String return value type replaces other types */@ Controllerpublic class HandleAjax {@ RequestMapping ("/ajax. do ") public void handleAjax (HttpServletResponse response) throws Exception {// forged Data Map <String, UserInfo> map = new HashMap <String, UserInfo> (); userInfo u1 = new UserInfo (); u1.setAge (12); u1.setName (""); UserInfo u2 = new UserInfo (); u2.setAge (122 ); u2.setName ("successful employment"); map. put ("001", u1); map. put ("001", u2); // tool map ---- json String fastjson String jsonString = JSON. toJSONString (map); response. setCharacterEncoding ("UTF-8"); return jsonString ;}

 

 

05. Redirect TO ANOTHER METHOD

/** Forward and redirect * to another method */@ Controllerpublic class Dispatchreturn {/** redirect to another method dsipatch. do */@ RequestMapping (value = "add. do ") public String AddAllInfo () {return" redirect: dolist. do ";}@ RequestMapping (value =" dolist. do ") public String doList () {return" redirect:/list. jsp ";}}

 

Note: "/" can be written or not.

 

Related Article

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.