一直以来对J2EE的开发有浓厚的兴趣,几款主流框架(SSH,SS2H等)都多多少少有些项目经验;因此,今天我将开始介绍我自认为构建、开发最为有效、最美的springMVC。
它的美有以下几点:
1、spring本省的强大,控制反转、数据源管理、aop、事务管理等...太多好处了。
2、只需要spring及其相关jar包,不需要struts等,因此不存在jar包整合问题。
3、自带完美的jdbctemplate,可以封装出各种dao操作,无论是传统jdbc的sql操作还是hibernate、mybatis的实体bean操作,都不成问题。不需借助其他持久层。
4、完美的注解机制,不再需要为开发某个新功能而配一大堆xml写一大堆实体bean。结合aop机制,也可以编写自己需要的注解。
5、对于REST架构,springmvc中的MethodHandlerAdapter能毫无压力的将对象转化成Json并返回给前端,简直是为REST而生。
以上几点对spring之美的看法是小弟我自己的理解,有异议的朋友可以在评论中指出,也好帮助小弟我不断成长。废话不多说,下面我们来看看如何在项目开发之前构建好一个springmvc开发框架。(文章最后有整个框架的源码下载链接,感兴趣的朋友可以下载,里面jar包都齐全)
com.springmvc.framework.BaseDao:封装了项目中用的到基本dao操作,当然需要的话可以封装更多的操作在里面
com.springmvc.util.BeanFactory:通过该类的静态方法你可以获取任何一个spring bean
system.properties:一些项目的配置信息可以放在该文件中,项目启动时会通过com.springmvc.sys.Systemup这个Servlet类将配置信息加载到内存中
sp-db.xml:配置spring数据源,及基本的bean注入
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName">
<!-- 数据源配置,不多说 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&rewriteBatchedStatements=true&noAccessToProcedureBodies=true" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="acquireIncrement" value="5"/>
<property name="preferredTestQuery" value="select count(1) from dual limit 1"/>
<property name="checkoutTimeout" value="20000"/>
<property name="idleConnectionTestPeriod" value="60"/>
<property name="initialPoolSize" value="10"/>
<property name="maxIdleTime" value="120"/>
<property name="maxPoolSize" value="50"/>
<property name="maxStatements" value="100"/>
<property name="numHelperThreads" value="3"/>
<property name="testConnectionOnCheckin" value="true"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<constructor-arg ref="dataSourceTransactionManager" />
</bean>
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" />
<bean id="baseDao" class="com.springmvc.framework.BaseDao" autowire="byName"></bean>
<!-- 通过该注入,可以使该类获取整个spring容器,因此可以获取任何容器中的bean -->
<bean class="com.springmvc.util.BeanFactory" autowire="byName"></bean>
</beans>
spring-servlet.xml:springmvc的配置
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 注册aop功能 -->
<aop:aspectj-autoproxy/>
<!-- 自动扫面com.springmvc目录及其子目录下面所有类文件,自动注入所有带注解的类 -->
<context:component-scan base-package="com.springmvc.*" />
<!-- 处理请求response返回值,如下配置能正确返回字符串型返回值,如返回值为对象,则自动转为json -->
<bean id="handleAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
<ref bean="mappingStringHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="mappingStringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp"></property>
<property name="order" value="1"></property>
</bean>
<!-- spring文件上传编码 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" />
</beans>
package com.springmvc.framework;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
@SuppressWarnings("unchecked")
public class BaseDao{
private JdbcTemplate jdbcTemplate;
private TransactionTemplate transactionTemplate;
private Logger log = Logger.getLogger(this.getClass().getName());
//获取记录,sql执行后有多少返回多少
public List<String[]> getRows(String sql) {
log.info(sql);
List<String[]> strs = (List<String[]>) this.jdbcTemplate.query(sql,
new ResultSetExtractor() {
public Object extractData(ResultSet rs)throws SQLException, DataAccessException{
ResultSetMetaData rsd = rs.getMetaData();
int num = rsd.getColumnCount();
List list = new ArrayList();
while (rs.next()) {
String[] strs = new String[num];
for (int i = 0; i < num; i++) {
strs[i] = rs.getString(i + 1);
}
list.add(strs);
}
return list;
}
});
return strs;
}
//获取记录,sql执行后有多少返回多少
public List<String[]> getRows(String sql, Object[] params) {
log.info(sql+" params:"+Arrays.toString(params));
List<String[]> strs = (List<String[]>) this.jdbcTemplate.query(sql,
params, new ResultSetExtractor() {
public Object extractData(ResultSet rs)
throws SQLException, DataAccessException {
ResultSetMetaData rsd = rs.getMetaData();
int num = rsd.getColumnCount();
List list = new ArrayList();
while (rs.next()) {
String[] strs = new String[num];
for (int i = 0; i < num; i++) {
strs[i] = rs.getString(i + 1);
}
list.add(strs);
}
return list;
}
});
return strs;
}
//获取单行记录
public synchronized String[] getRow(String sql) {
List<String[]> list = this.getRows(sql);
if (list.size() == 0)
return null;
else
return list.get(0);
}
//获取单行记录
public synchronized String[] getRow(String sql, Object[] params) {
List<String[]> list = this.getRows(sql, params);
if (list.size() == 0)
return null;
else
return list.get(0);
}
//执行单条sql insert、update、delete
public int execute(String sql) {
log.info(sql);
int r = this.jdbcTemplate.update(sql);
return r;
}
//prepared式执行单条sql
public int execute(String sql, Object[] params) {
log.info(sql+" params:"+Arrays.toString(params));
int r = this.jdbcTemplate.update(sql, params);
return r;
}
//批量执行sql
public void executeBatch(List<String> sql) {
log.info(sql);
String[] ss = new String[sql.size()];
for(int is=0 ; is<sql.size() ; is++){
ss[is] = sql.get(is);
}
final String[] sqls = ss;
this.transactionTemplate.execute(new TransactionCallbackWithoutResult(){
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try{
jdbcTemplate.batchUpdate(sqls);
}catch(Exception e){
status.setRollbackOnly();
}
}
});
}
//prepared式批量执行insert,update,delete
public void executeBatch(String sql, final List<Object[]> params) {
log.info(sql);
this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
public int getBatchSize() {
return params.size();
}
public void setValues(PreparedStatement ps, int i)
throws SQLException {
Object[] o = params.get(i);
for (int y = 0; y < o.length; y++) {
ps.setObject(y + 1, o[y]);
}
log.info("params:"+Arrays.toString(o));
}
});
}
//调用存储过程
public synchronized void call(String prc) throws SQLException {
log.info("call:"+prc);
this.getJdbcTemplate().execute("{CALL "+prc+"}", new CallableStatementCallback(){
public Object doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
cs.execute();
return null;
}
});
log.info("end call:"+prc);
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public TransactionTemplate getTransactionTemplate() {
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
}
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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 com.springmvc.dao.TestDao;
@Controller
@RequestMapping("/test.action")
public class TestAction {
//有了@Autowired注解,该属性不需要getter、setter方法也能被spring注入,变量命名必须是首字母小写的类名
@Autowired
private TestDao testDao;
//请求某个jsp页面
@RequestMapping(params = "operate=helloworld")
public String helloworld(String name) throws IOException {
//调用数据操作
this.testDao.dosomething();
return "index";
}
//被@ResponseBody标记的返回值相当于是 response.getWriter().println(...);如果返回值某个实体对象,则会自动转成json返回
@RequestMapping(params = "operate=ajax")
public @ResponseBody Object ajax(String name) throws IOException {
return name;
}
//在spring中,你也可以随意的使用传统的request、response和session
@RequestMapping(params = "operate=mtd1")
public void mtd1(HttpServletResponse response,HttpServletRequest request,HttpSession session) throws IOException {
String param = request.getParameter("param");
session.setAttribute("param", param);
response.getWriter().println(param);
}
}
TestDao:
package com.springmvc.dao;
import com.springmvc.framework.IBaseDao;
public class TestDao extends IBaseDao{
public String[] dosomething() {
String[] row = this.baseDao.getRow("select 1 from dual");
row = this.baseDao.getRow("select * from book where book_id=?",new Object[]{"1"});
return row;
}
}
源码下载:http://download.csdn.net/detail/enzetianxia/6218783