首页 > 代码库 > 使用SpringMVC+mybatis+事务控制+JSON 配置最简单WEB
使用SpringMVC+mybatis+事务控制+JSON 配置最简单WEB
最近在总结一些项目的基础知识,根据公司最近的一些意向和技术路线,初步整理了一个简单的配置例子
1.使用springmvc代替strutsMVC
2.使用请求json数据串的方式代替传统返回jspview。
3.使用Mybatis代替hibernate
在这些要求的基础上,做了一些尝试。
现在将配置文件整理如下:
目录结构如下:
1.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>standard</display-name> <context-param> <param-name>webAppRootKey</param-name> <param-value>standard.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext.xml </param-value> </context-param> <filter> <filter-name>CharacterEncodingFilter</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:standard-context.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list></web-app>
2.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!--加入过滤的配置是为了使mybatis的事务起作用--> <context:component-scan base-package="cn.telchina.standard" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:property-placeholder location="classpath*:jdbc.properties" ignore-resource-not-found="true" system-properties-mode="OVERRIDE" ignore-unresolvable="true"/> <!-- jdbc.propertis Directory --> <!-- 定义主数据库的数据库连接--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${jdbc.driver}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.user}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="cn.telchina.standard.entity" /> <property name="configLocation" value="classpath:mybatisConfig.xml"></property> <property name="mapperLocations" value="classpath*:sql-mappers/*.xml" /> </bean> <!-- 通过扫描的模式,扫描目录在com/hoo/mapper目录下,所有的mapper都继承SqlMapper接口的接口, 这样一个bean就可以了 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.telchina.standard.mapper"/> </bean> <!-- 进行主数据库的事务配置,采用默认策略 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /></beans>
3.standard-context.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- Spring会扫描该包路径下的所有类,并将有注解定义的Bean进行自动装配和实现Bean之间自动依赖注入,城管项目人员不需要修改 --> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <!--加入过滤的配置是为了使mybatis的事务起作用--> <context:component-scan base-package="cn.telchina.standard" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <context:annotation-config /> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven/> <!--如果在web.xml中配置的是拦截“/”,需要在此配置放过/scripts下的静态文件 <mvc:resources mapping="/scripts/**" location="/scripts/" /> --> <!-- annotation默认的方法映射适配器 <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --></beans>
4.mybatisConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <!-- 配置mybatis的缓存,延迟加载等等一系列属性 --> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> <!-- <setting name="useGeneratedKeys" value=http://www.mamicode.com/"true" /> --> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="FULL" /> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="BATCH" /> <!-- 数据库超过25000秒仍未响应则超时 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 --> <!-- <typeAliases> <typeAlias alias="TestBean" type="com.wotao.taotao.persist.test.dataobject.TestBean" /> </typeAliases> --> <!-- 非注解的sql映射文件配置,如果使用mybatis注解,该mapper无需配置,但是如果mybatis注解中包含@resultMap注解,则mapper必须配置,给resultMap注解使用 --> <!-- <mappers> <mapper resource="com/mybatis/mapper/UserMapper.xml" /> </mappers> --></configuration>
5.*mapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.telchina.standard.mapper.UserMapper"> <!-- 只能使用【${变量}】的方式,不能使用【#{变量}】的方式 ,${变量}将传入的数据直接显示生成在sql中。--> <!-- <![CDATA[sql ]]> 尽量每个sql必须写,防止有些特殊字符对sql语句造成的破坏 --> <select id="getUser" resultType="SysUserModel" > select * from sys_user where usercode= #{usercode} </select> <insert id="insertUser" parameterType="SysUserModel"> insert into sys_user (id,usercode,password,loginstate,lastlogin,personcode,delflag,remarks,userorder,opentype) values (#{id},#{userCode},#{passWord},#{loginState},#{lastLogin},#{personCode},#{delFlag},#{remarks},#{userOrder},#{openType}) </insert></mapper>
6.JavaBean.java
package cn.telchina.standard.entity;import java.util.Date;public class SysUserModel { // 编号 private int id; // 用户编码 private String userCode; // 用户密码 private String passWord; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; }}
7.Mapper.java
package cn.telchina.standard.mapper;import cn.telchina.standard.entity.SysUserModel;public interface UserMapper { public SysUserModel getUser(String usercode); public void insertUser(SysUserModel usermodel);}
8.Service.java
package cn.telchina.standard.model1.service;import java.util.Random;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import cn.telchina.standard.entity.SysUserModel;import cn.telchina.standard.mapper.UserMapper;@Servicepublic class TestService { @Autowired private UserMapper userMapper; Logger log = Logger.getLogger(this.getClass()); @Transactional(rollbackFor=Exception.class) public void dboperate() { SysUserModel usermodel = userMapper.getUser("admin"); log.info(usermodel); int i=(new Random()).nextInt(100); usermodel.setId(i); usermodel.setUserCode(usermodel.getUserCode() + i); userMapper.insertUser(usermodel);// if (true) {// throw new RuntimeException("异常测试");// } }}
9.Controller.java
package cn.telchina.standard.model1.controller;import java.util.HashMap;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import cn.telchina.standard.model1.service.TestService;import com.alibaba.fastjson.JSON;@Controllerpublic class TestController { @Autowired private TestService testservice; @ResponseBody @RequestMapping("/test") public String getJsonString(String para1,String para2) { testservice.dboperate(); HashMap<String,String> user = new HashMap<String,String>(); user.put("para1", para1); user.put("para2", para2); return JSON.toJSONString(user); }}
10.html文件
$(function() { $(‘#send‘).click(function() { $.ajax({ type : "GET", url : "test.json", data: {para1:"para1",para2:"para2"}, dataType:"json", success:function(data){ console.log(data); } }); }); });
作者:sdjnzqr
出处:http://www.cnblogs.com/sdjnzqr/
版权:本文版权归作者和博客园共有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
出处:http://www.cnblogs.com/sdjnzqr/
版权:本文版权归作者和博客园共有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。