少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          //web.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <web-app xmlns:xsi=" xmlns="http://java.sun.com/xml/ns/javaee  id="WebApp_ID" version="3.0">
           <display-name>universal</display-name>
           <!-- spring -->
           <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:com/abin/lee/ssh/spring-service.xml</param-value>
           </context-param>
           <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
           </listener>


           <!-- spring MVC -->
           <servlet>
            <servlet-name>spring-mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath*:com/abin/lee/ssh/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>2</load-on-startup>
           </servlet>
           <servlet-mapping>
            <servlet-name>spring-mvc</servlet-name>
            <url-pattern>/mvc/*</url-pattern>
           </servlet-mapping>
           <!-- spring encoding -->
           <filter>
            <filter-name>utf8-encoding</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>utf8-encoding</filter-name>
            <url-pattern>/*</url-pattern>
           </filter-mapping>

           


           <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
           </welcome-file-list>
          </web-app>





          //spring-mvc.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="
           xmlns:xsi=" xmlns:context=" xmlns:mvc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/util  <!-- 指定系統(tǒng)尋找controller路徑 -->
           <mvc:annotation-driven>
            <!-- json 數(shù)據(jù)格式轉(zhuǎn)換-->
            <mvc:message-converters>
             <bean class="com.abin.lee.ssh.function.FastJsonAbstractHttpMessageConverter">
              <property name="supportedMediaTypes" value="application/json" />
              <property name="serializerFeature">
               <list>
                <value>WriteMapNullValue</value>
                <value>QuoteFieldNames</value>
               </list>
              </property>
             </bean>
            </mvc:message-converters>

           </mvc:annotation-driven>
           <!-- 搜索的包路徑 -->
           <context:component-scan base-package="com.abin.lee.ssh"
            use-default-filters="false">
            <context:include-filter type="annotation"
             expression="org.springframework.stereotype.Controller" />
           </context:component-scan>

          </beans>





          //spring-service.xml
          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="
           xmlns:xsi=" xmlns:context=" xmlns:jdbc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
              http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
              http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
              http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd 
              http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd 
             http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-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/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd 
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
              http://www.springframework.org/schema/util  
           <context:annotation-config />
           <context:component-scan base-package="com.abin.lee.ssh"></context:component-scan>
           
           <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"       
                  destroy-method="close">      
              <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>      
              <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe"/>      
              <property name="user" value="abin"/>      
              <property name="password" value="abin"/>      
           </bean>
           
           <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource">
             <ref bean="dataSource" />
            </property>
            <property name="hibernateProperties">
             <props>
              <prop key="hibernate.dialect">
               org.hibernate.dialect.OracleDialect
              </prop>
              <prop key="hibernate.show_sql">
               true
              </prop>
              <prop key="hibernate.show_sql">true</prop>
              <prop key="hibernate.format_sql">true</prop>
              <prop key="hibernate.hbm2ddl.auto">update</prop>
             </props>
            </property>
            <!--主鍵Bean類
            <property name="annotatedClasses">
             <list>
              <value>com.abin.lee.ssh.entity.ModeBean</value>
             </list>
            </property>
             -->
            <!-- 自動(dòng)掃描-->
             <property name="packagesToScan" value="com.abin.lee.ssh.entity" />
           </bean>
           
           <!-- 配置事務(wù)管理器 -->
           <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory">
             <ref bean="sessionFactory" />
            </property>
           </bean>
           
           <!-- 配置注解實(shí)現(xiàn)管理事務(wù)(cglib:proxy-target-class="true") -->
           <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
           <!-- 指定使用cglib -->
           <!--   -->
           <aop:aspectj-autoproxy proxy-target-class="true" />
           
           <!-- 配置事務(wù)的傳播特性 -->
           <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
             <tx:method name="save*" propagation="REQUIRED" />
             <tx:method name="insert*" propagation="REQUIRED" />
             <tx:method name="update*" propagation="REQUIRED" />
             <tx:method name="delete*" propagation="REQUIRED" />
             <tx:method name="*" read-only="false" />
            </tx:attributes>
           </tx:advice>
           
           <!-- 那些類的哪些方法參與事務(wù)-->
           <aop:config>
            <aop:pointcut id="allServiceMethod" expression="execution(* com.abin.lee.ssh.spring.*.*(..))" />
            <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
           </aop:config>
           
          </beans>



          //FastJsonAbstractHttpMessageConverter.java

          package com.abin.lee.ssh.function;

          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.OutputStream;
          import java.net.URLDecoder;
          import java.nio.charset.Charset;

          import org.springframework.http.HttpInputMessage;
          import org.springframework.http.HttpOutputMessage;
          import org.springframework.http.MediaType;
          import org.springframework.http.converter.AbstractHttpMessageConverter;
          import org.springframework.http.converter.HttpMessageNotReadableException;
          import org.springframework.http.converter.HttpMessageNotWritableException;
          import org.springframework.util.FileCopyUtils;

          import com.alibaba.fastjson.JSON;
          import com.alibaba.fastjson.serializer.SerializerFeature;

          //來對(duì)requestbody 或responsebody中的數(shù)據(jù)進(jìn)行解析
          public class FastJsonAbstractHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
            public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
           // fastjson特性參數(shù) 
              private SerializerFeature[] serializerFeature; 
           
              public SerializerFeature[] getSerializerFeature() { 
                  return serializerFeature; 
              } 
           
              public void setSerializerFeature(SerializerFeature[] serializerFeature) { 
                  this.serializerFeature = serializerFeature; 
              } 
           
           //限定頁面文本傳送類型 只有數(shù)據(jù)是改類型 的 才會(huì)進(jìn)行攔截
           //application/json
           public FastJsonAbstractHttpMessageConverter(){
          //  super(new MediaType("text","plain"));
            super(new MediaType("application","json"));
           }
           @Override
           protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputmessage) throws IOException,
             HttpMessageNotReadableException {
            Charset charset;
            MediaType mediaType=inputmessage.getHeaders().getContentType();
            if(mediaType!=null&&mediaType.getCharSet()!=null){
             charset=mediaType.getCharSet();
            }else{
             charset=Charset.forName("UTF-8");
            }
            
            String input=FileCopyUtils.copyToString(new InputStreamReader(inputmessage.getBody(),charset));
            String result=URLDecoder.decode(input, "UTF-8");
            System.out.println(result);
            /*OrgnizationPO po=new OrgnizationPO();
            po.setId(1);
            po.setName("11");
            po.setOrgdesc("1");*/
            
            /*ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                  int i; 
                  while ((i = inputmessage.getBody().read()) != -1) { 
                      baos.write(i); 
                  }  */
                  return JSON.parseObject(result, clazz);
          //        return JSON.parseArray(baos.toString(), clazz);
          //  return po;
           }

           @Override
           protected boolean supports(Class<?> clazz) {
            return true;
            //throw new UnsupportedOperationException();
           }

           @Override
           protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
             HttpMessageNotWritableException {
            String jsonString = JSON.toJSONString(o, serializerFeature); 
          //  System.out.println(jsonString);
                  OutputStream out = outputMessage.getBody(); 
                  out.write(jsonString.getBytes(DEFAULT_CHARSET)); 
                  out.flush(); 
           }

          }






          package com.abin.lee.ssh.hibernate;

          import com.abin.lee.ssh.entity.ModeBean;

          public interface ModeDao {
           public boolean insert(ModeBean mode);
          }




          package com.abin.lee.ssh.hibernate.impl;

          import javax.annotation.Resource;

          import org.hibernate.SessionFactory;
          import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
          import org.springframework.stereotype.Repository;

          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.hibernate.ModeDao;
          @Repository
          public class ModeDaoImpl extends HibernateDaoSupport implements ModeDao{
           
           @Resource(name = "sessionFactory")
           public void setSuperSessionFactory(SessionFactory sessionFactory) {
            super.setSessionFactory(sessionFactory);
           }
           
           public boolean insert(ModeBean mode) {
            boolean flag=false;
            try {
             this.getHibernateTemplate().saveOrUpdate(mode);
             flag=true;
            } catch (Exception e) {
             e.printStackTrace();
            }
            return flag;
           }
           
           
          }






          package com.abin.lee.ssh.spring;

          import com.abin.lee.ssh.entity.ModeBean;

          public interface ModeService {
           public boolean insert(ModeBean mode);

          }





          package com.abin.lee.ssh.spring.impl;

          import javax.annotation.Resource;

          import org.springframework.stereotype.Service;
          import org.springframework.transaction.annotation.Isolation;
          import org.springframework.transaction.annotation.Propagation;
          import org.springframework.transaction.annotation.Transactional;

          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.hibernate.ModeDao;
          import com.abin.lee.ssh.spring.ModeService;

          @Service
          @Transactional(readOnly = true, timeout = 2, propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
          public class ModeServiceImpl implements ModeService {
           @Resource
           private ModeDao modeDao;

           @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
           public boolean insert(ModeBean mode) {
            boolean flag = false;
            try {
             flag = this.modeDao.insert(mode);
            } catch (Exception e) {
             e.printStackTrace();
            }
            return flag;
           }

          }






          package com.abin.lee.ssh.springmvc;

          import javax.annotation.Resource;

          import org.springframework.stereotype.Controller;
          import org.springframework.web.bind.annotation.ModelAttribute;
          import org.springframework.web.bind.annotation.RequestMapping;
          import org.springframework.web.bind.annotation.RequestMethod;
          import org.springframework.web.bind.annotation.ResponseBody;

          import com.abin.lee.ssh.dto.request.ModeRequest;
          import com.abin.lee.ssh.dto.response.ModeResponse;
          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.spring.ModeService;

          @Controller
          @RequestMapping("/stevenjohn/")
          public class ModeController {
           @Resource
           private ModeService modeService;

           @RequestMapping(value = "getMode", method = RequestMethod.POST)
           public @ResponseBody
           ModeResponse getMode(
             @ModelAttribute ModeRequest modeRequest) {
            ModeResponse response = new ModeResponse();
            String id=modeRequest.getId();
            String username=modeRequest.getUsername();
            String password=modeRequest.getPassword();
            int age=modeRequest.getAge();
            String address=modeRequest.getAddress();
            String email=modeRequest.getEmail();
            ModeBean mode=new ModeBean(id, username, password, age, address, email);
            boolean flag=modeService.insert(mode);
            System.out.println("flag="+flag);
            if(flag==true){
             response.setStatus("success");
            }else{
             response.setStatus("failure");
            }
            
            return response;
           }
          }




          package com.abin.lee.ssh.entity;

          import java.io.Serializable;

          import javax.persistence.Column;
          import javax.persistence.Entity;
          import javax.persistence.Id;
          import javax.persistence.Table;
          @Entity
          @Table(name="MODEBEAN")
          public class ModeBean implements Serializable{
           @Id
           @Column(name="ID")
           private String id;
           @Column(name="USERNAME",length=100,nullable=true)
           private String username;
           @Column(name="PASSWORD",length=100,nullable=true)
           private String password;
           @Column(name="AGE",length=10,nullable=true)
           private int age;
           @Column(name="ADDRESS",length=100,nullable=true)
           private String address;
           @Column(name="EMAIL",length=100,nullable=true)
           private String email;
           public ModeBean() {
           }
           public ModeBean(String id, String username, String password, int age,
             String address, String email) {
            super();
            this.id = id;
            this.username = username;
            this.password = password;
            this.age = age;
            this.address = address;
            this.email = email;
           }
           
           public String getId() {
            return id;
           }
           public void setId(String id) {
            this.id = id;
           }
           public String getUsername() {
            return username;
           }
           public void setUsername(String username) {
            this.username = username;
           }
           public String getPassword() {
            return password;
           }
           public void setPassword(String password) {
            this.password = password;
           }
           public int getAge() {
            return age;
           }
           public void setAge(int age) {
            this.age = age;
           }
           public String getAddress() {
            return address;
           }
           public void setAddress(String address) {
            this.address = address;
           }
           public String getEmail() {
            return email;
           }
           public void setEmail(String email) {
            this.email = email;
           }
           
           
          }







          //SpringMVC請(qǐng)求參數(shù)

          package com.abin.lee.ssh.dto.request;

          import java.io.Serializable;

          public class ModeRequest implements Serializable{
           /**
            *
            */
           private static final long serialVersionUID = 1886596479119297989L;
           private String id;
           private String username;
           private String password;
           private int age;
           private String address;
           private String email;
           public String getId() {
            return id;
           }
           public void setId(String id) {
            this.id = id;
           }
           public String getUsername() {
            return username;
           }
           public void setUsername(String username) {
            this.username = username;
           }
           public String getPassword() {
            return password;
           }
           public void setPassword(String password) {
            this.password = password;
           }
           public int getAge() {
            return age;
           }
           public void setAge(int age) {
            this.age = age;
           }
           public String getAddress() {
            return address;
           }
           public void setAddress(String address) {
            this.address = address;
           }
           public String getEmail() {
            return email;
           }
           public void setEmail(String email) {
            this.email = email;
           }
           
          }





          //SpringMVC響應(yīng)參數(shù)


          package com.abin.lee.ssh.dto.response;

          import java.io.Serializable;

          public class ModeResponse implements Serializable{
           /**
            *
            */
           private static final long serialVersionUID = 7725619232731203410L;
           private String status;
           private String message;
           public ModeResponse() {
           }
           public ModeResponse(String status, String message) {
            super();
            this.status = status;
            this.message = message;
           }
           public String getStatus() {
            return status;
           }
           public void setStatus(String status) {
            this.status = status;
           }
           public String getMessage() {
            return message;
           }
           public void setMessage(String message) {
            this.message = message;
           }
           
          }




          //log4j.properties

          log4j.rootCategory=info,log,console

          log4j.logger.org.apache.axis2.enterprise=FATAL
          log4j.logger.de.hunsicker.jalopy.io=FATAL
          log4j.logger.httpclient.wire.header=FATAL
          log4j.logger.org.apache.commons.httpclient=FATAL

          log4j.appender.console=org.apache.log4j.ConsoleAppender
          log4j.appender.console.layout=org.apache.log4j.PatternLayout
          log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
           
          log4j.appender.log=org.apache.log4j.DailyRollingFileAppender
          log4j.appender.log.File=../logs/mms.log
          log4j.appender.log.layout=org.apache.log4j.PatternLayout
          log4j.appender.log.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n








          //測試springMVC的Junit4+httpClient類:

          package com.abin.lee.ssm;

          import java.io.BufferedReader;
          import java.io.InputStreamReader;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.UUID;

          import junit.framework.TestCase;

          import org.apache.http.HttpResponse;
          import org.apache.http.NameValuePair;
          import org.apache.http.client.HttpClient;
          import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.HttpPost;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.message.BasicNameValuePair;
          import org.apache.http.protocol.HTTP;
          import org.junit.Test;

          public class HttpsClient extends TestCase {
           private String httpUrl = "
          http://localhost:7000/universal/mvc/stevenjohn/getMode";

           @Test
           public void testHttpsClient() {
            try {
             HttpClient httpClient = new DefaultHttpClient();
             HttpPost httpPost = new HttpPost(httpUrl);
             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
             nvps.add(new BasicNameValuePair("id", UUID.randomUUID().toString()));
             nvps.add(new BasicNameValuePair("username", "abin"));
             nvps.add(new BasicNameValuePair("password", "abing"));
             nvps.add(new BasicNameValuePair("age", "28"));
             nvps.add(new BasicNameValuePair("address", "beijing of china"));
             nvps.add(new BasicNameValuePair("email", "varyall@tom.com"));
             httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
             HttpResponse httpResponse = httpClient.execute(httpPost);
             BufferedReader buffer = new BufferedReader(new InputStreamReader(
               httpResponse.getEntity().getContent()));
             StringBuffer stb=new StringBuffer();
             String line=null;
             while((line=buffer.readLine())!=null){
              stb.append(line);
             }
             buffer.close();
             String result=stb.toString();
             System.out.println("result="+result);
            } catch (Exception e) {
             e.printStackTrace();
            }

           }

          }

          posted on 2012-10-21 01:12 abin 閱讀(3943) 評(píng)論(1)  編輯  收藏 所屬分類: spring

          Feedback

          # re: SpringMVC Spring3 Hibernate3.3全注解 2013-09-18 17:00 Mr彭
          長知識(shí)!  回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 旺苍县| 常熟市| 郯城县| 依兰县| 安龙县| 新平| 金堂县| 吉林省| 乃东县| 长岭县| 招远市| 红河县| 张家川| 巴彦淖尔市| 闽清县| 莱芜市| 铁岭县| 辽源市| 保德县| 和政县| 靖远县| 田林县| 姜堰市| 巴马| 重庆市| 锡林郭勒盟| 桐柏县| 宽甸| 宜都市| 乐亭县| 连州市| 三都| 沂水县| 疏勒县| 星子县| 冕宁县| 买车| 澳门| 南乐县| 新和县| 博爱县|