SpringMVC @Autowired

来源:互联网 发布:bind javascript 编辑:程序博客网 时间:2024/05/24 03:56
package com.liyang;import  com.alibaba.fastjson.JSON;import  com.alibaba.fastjson.JSONObject ;public class Address {       private  String  line1 ;       private  String  line2 ;       private  String  city ;       private  String  state ;       private  String  zipCode ;       private  String  country  ;        public String getLine1() {            return line1;        }        public void setLine1(String line1) {            this.line1 = line1;        }        public String getLine2() {            return line2;        }        public void setLine2(String line2) {            this.line2 = line2;        }        public String getCity() {            return city;        }        public void setCity(String city) {            this.city = city;        }        public String getState() {            return state;        }        public void setState(String state) {            this.state = state;        }        public String getZipCode() {            return zipCode;        }        public void setZipCode(String zipCode) {            this.zipCode = zipCode;        }        public String getCountry() {            return country;        }        public void setCountry(String country) {            this.country = country;        }        public  Address(){ //一定要有        }       public  Address(String line1 , String line2 , String city ,                       String state , String zipCode , String country){               this.line1 = line1 ;               this.line2 = line2 ;               this.city  = city ;               this.state = state ;               this.zipCode = zipCode ;               this.country = country  ;       }       @Override       public String toString(){              return  JSONObject.toJSONString(this) ;       }}
package com.liyang;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;public class Employee  {       private   String  firstName ;       private   String  lastName ;       @Autowired       private   Address  homeAddress ;       public String getFirstName() {            return firstName;       }       public void setFirstName(String firstName) {            this.firstName = firstName;       }       public String getLastName() {            return lastName;       }       public void setLastName(String lastName) {            this.lastName = lastName;       }       public Address getHomeAddress() {            return homeAddress;       }       public void setHomeAddress(Address homeAddress) {            this.homeAddress = homeAddress;       }       public  Employee(String firstName , String lastName , Address homeAddress){               this.firstName = firstName ;               this.firstName = lastName ;               this.homeAddress = homeAddress ;       }       public  Employee(){ //一定要有       }       @Override       public String toString() {              return  JSONObject.toJSONString(this) ;      }}
package com.liyang;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.lang.annotation.Annotation;import java.util.Date;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.codehaus.jackson.map.ObjectMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.portlet.bind.annotation.RenderMapping;import org.springframework.web.servlet.ModelAndView;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.sun.corba.se.spi.orbutil.fsm.Input;import com.sun.org.apache.regexp.internal.recompile;import com.sun.xml.internal.ws.util.StreamUtils;@Controllerpublic class HelloContorller implements Controller{       @Autowired       private  Employee  employee   ;       @RequestMapping(value="miss.do")       @ResponseBody       public ModelAndView handleRequest(HttpServletRequest request) throws Exception{                  ModelAndView mav = new ModelAndView("messge");                  mav.addObject("miss", "I miss you!" );                  Map<String , Object> param = ProcessHttpParamsToMap(request) ;                System.out.println("who=" + param.get("who")) ;                mav.addObject("who", param.get("who") );                  return mav;         }//跳到页面       @RequestMapping(value="employee.do")       @ResponseBody       public ModelMap handleEmployee(HttpServletRequest request) throws Exception{                ModelMap modl = new ModelMap() ;              modl.put("messge", employee ) ;              return modl ;         }//跳到页面       @RequestMapping(value="miss2.do")       @ResponseBody       public ModelAndView handleRequest2(HttpServletRequest request) throws Exception{                  return new ModelAndView("page_1") ;       }//跳到页面       @RequestMapping(value="login.do")       @ResponseBody       public ModelAndView handleRequestLogin(HttpServletRequest request) throws Exception{                ModelAndView mdv = new ModelAndView("login") ;              Map<String , Object> param = ProcessHttpParamsToMap(request) ;              System.out.println("show = " + param.get("username")) ;              System.out.println("show = " + param.get("password")) ;              mdv.addObject("username" , param.get("username")) ;               mdv.addObject("password" , param.get("password")) ;               return  mdv ;       }//跳到页面       @RequestMapping(value="showlogin.do" , produces="text/html;charset=UTF-8")       @ResponseBody       public ModelAndView handleRequestShowLogin(HttpServletRequest request) throws Exception{                ModelAndView mdv = new ModelAndView("showlogin") ;              Map<String , Object> param = ProcessHttpParamsToMap(request) ;              System.out.println("show = " + param.get("username")) ;              System.out.println("show = " + param.get("password")) ;              mdv.addObject("username" , param.get("username")) ;               mdv.addObject("password" , param.get("password")) ;               return  mdv ;       }//跳到页面       @RequestMapping(value="say.do")       @ResponseBody       public ModelMap say(HttpServletRequest request){              ModelMap mod = new ModelMap() ;              mod.put("a", "_a") ;              mod.put("z", "_z") ;              mod.put("c", "_c") ;              mod.put("b", "_b") ;              return  mod  ;        }// 返回的是json格式       @RequestMapping(value="ask.do", produces="text/html;charset=UTF-8")       @ResponseBody       public String ask(HttpServletRequest request) throws IOException{              Map<String , Object> param = ProcessHttpParamsToMap(request) ;              try{              }catch(Exception e){                  e.printStackTrace() ;               }              return "something int [Ask] is error!" ;       }       @RequestMapping(value="hi.do", produces="text/html;charset=UTF-8")       @ResponseBody       public String hi(HttpServletRequest request) throws IOException{              Map<String , Object> param = ProcessJosnParamsToMap(request) ;              try{                  return JSONObject.toJSONString(param) ;              }catch(Exception e){                  e.printStackTrace() ;               }              return "something int [Hi] is error!" ;       }       public static byte[] readStreamToBytes(InputStream inputStream) throws IOException{                 ByteArrayOutputStream out = new ByteArrayOutputStream();                 byte[] buffer = new byte[1024];                 int len = 0;                 while ((len = inputStream.read(buffer)) != -1) {                       out.write(buffer, 0, len);                 }                 out.close();                 inputStream.close();                 return out.toByteArray();           }       private Map<String, Object> ProcessHttpParamsToMap(HttpServletRequest request) throws UnsupportedEncodingException{               String charest = request.getCharacterEncoding() ;               if(charest == null || charest.isEmpty())                     request.setCharacterEncoding("UTF-8") ;               Map<String, String[]>  params = request.getParameterMap()  ;               Map<String , Object> datas = new HashMap<String , Object>() ;               if (params == null || params.isEmpty()){                    return datas;               }               for(Map.Entry<String , String[]> e : params.entrySet()){                       if(e.getKey().length() > 0) datas.put(e.getKey(), e.getValue()[0].trim()) ;               }               return datas;        }        private Map<String , Object> ProcessJosnParamsToMap(HttpServletRequest request) throws IOException{               InputStream inputStream = request.getInputStream() ;               String charest = request.getCharacterEncoding() ;               if(charest == null || charest.isEmpty()){                     charest = "UTF-8" ;               }               String requestStr =  new String(readStreamToBytes(inputStream) , charest) ;               System.out.println(requestStr);               ObjectMapper objectMapper = new ObjectMapper();               Map<String, Object> paramMap;               paramMap = objectMapper.readValue(requestStr, Map.class);               return  paramMap ;         }        @Override        public Class<? extends Annotation> annotationType() {            // TODO Auto-generated method stub              return null;        }        @Override        public String value() {            // TODO Auto-generated method stub               return null;        }}

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xmlns="http://java.sun.com/xml/ns/javaee"          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"          id="WebApp_ID"          version="3.0">  <servlet>           <servlet-name>dispatcherServlet</servlet-name>           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>           <load-on-startup>1</load-on-startup>     </servlet>     <servlet-mapping>           <servlet-name>dispatcherServlet</servlet-name>           <url-pattern>/</url-pattern>     </servlet-mapping>  </web-app>

dispatcherServlet-servlet.xml

<?xml version="1.0" encoding= "UTF-8"?><beans default-autowire="byName"       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:mvc="http://www.springframework.org/schema/mvc"       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.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">  <mvc:annotation-driven/>  <mvc:default-servlet-handler/>  <context:component-scan base-package="com.liyang"/>      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>     <property name="prefix" value="/WEB-INF/"></property>     <property name="suffix" value=".jsp"></property>   </bean>     <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>      <bean id = "addr" class="com.liyang.Address" >        <property name="line1" value="熊刘"></property>        <property name="line2" value="张港"></property>        <property name="city" value="天门"></property>        <property name="state" value="湖北"></property>        <property name="zipCode" value="431726"></property>        <property name="country" value="中国"></property>    </bean>    <bean  id = "employee" class = "com.liyang.Employee">           <property name="firstName"  value="老"> </property>           <property name="lastName"   value="李"> </property>           <property name="homeAddress" ref="addr"></property>    </bean> </beans>

http://localhost:8080/Hello/employee.do
{“messge”:{“firstName”:”老”,”lastName”:”李”,”homeAddress”:{“line1”:”熊刘”,”line2”:”张港”,”city”:”天门”,”state”:”湖北”,”zipCode”:”431726”,”country”:”中国”}}}

0 0
原创粉丝点击