简单之美.篇一.springMVC简单之道

一直以来对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

时间: 2024-08-29 17:41:36

简单之美.篇一.springMVC简单之道的相关文章

[原创]linux简单之美(三)

原文链接:linux简单之美(三) 在linux简单之美(二)中我们尝试使用了C库的函数完成功能,那么能不能用syscall方式来搞呢?显然可以! 1 section .data 2 ft db "now is X",10 3 4 section .text 5 global _start 6 7 _start: 8 mov edi,10 9 again: 10 dec edi 11 mov eax,edi 12 add eax,0x30 13 mov byte [ft+7],al 1

iOS开发UI篇—xib的简单使用

iOS开发UI篇—xib的简单使用 一.简单介绍 xib和storyboard的比较,一个轻量级一个重量级. 共同点: 都用来描述软件界面 都用Interface Builder工具来编辑 不同点: Xib是轻量级的,用来描述局部的UI界面 Storyboard是重量级的,用来描述整个软件的多个界面,并且能展示多个界面之间的跳转关系 二.xib的简单使用 1.建立xib文件 建立的xib文件命名为appxib.xib 2.对xib进行设置 根据程序的需要,这里把view调整为自由布局 建立vie

文顶顶 iOS开发UI篇—xib的简单使用

iOS开发UI篇—xib的简单使用 一.简单介绍 xib和storyboard的比较,一个轻量级一个重量级. 共同点: 都用来描述软件界面 都用Interface Builder工具来编辑 不同点: Xib是轻量级的,用来描述局部的UI界面 Storyboard是重量级的,用来描述整个软件的多个界面,并且能展示多个界面之间的跳转关系 二.xib的简单使用 1.建立xib文件 建立的xib文件命名为appxib.xib 2.对xib进行设置 根据程序的需要,这里把view调整为自由布局 建立vie

[原创]linux简单之美(二)

原文链接:linux简单之美(二) 我们在前一章中看到了如何仅仅用syscall做一些简单的事,现在我们看能不能直接调用C标准库中的函数快速做一些"复杂"的事: 1 section .data 2 ft db "now is %d",10 3 4 section .text 5 extern puts 6 extern exit 7 extern sleep 8 extern printf 9 global main 10 11 main: 12 mov edi,1

[原创]linux简单之美(一)

原文链接:linux简单之美(一) 话说windows也有syscall,这是必须的.但是win的syscall可以直接call吗?可以是可以但是破费周折,搞成SDT之类的复杂概念.下面看看linux是如何做的吧. 1 section .data 2 msg db "hello hopy!",0x0a 3 4 section .text 5 global _start 6 7 _start: 8 mov eax,4 9 mov ebx,1 10 mov ecx,msg 11 mov e

OS开发UI篇—xib的简单使用

OS开发UI篇—xib的简单使用 一.简单介绍 xib和storyboard的比较,一个轻量级一个重量级. 共同点: 都用来描述软件界面 都用Interface Builder工具来编辑 不同点: Xib是轻量级的,用来描述局部的UI界面 Storyboard是重量级的,用来描述整个软件的多个界面,并且能展示多个界面之间的跳转关系 二.xib的简单使用 1.建立xib文件 建立的xib文件命名为appxib.xib 2.对xib进行设置 根据程序的需要,这里把view调整为自由布局 建立view

iOS开发UI篇—实现一个简单的手势解锁应用(基本)

iOS开发UI篇—实现一个简单的手势解锁应用(基本) 一.实现效果 实现效果图: 二.手势解锁应用分析 1.监听手指在view上的移动,首先肯定需要自定义一个view,重写touch began,touch move等方法,当手指移动到圈上时,让其变亮.可以通过button按钮来实现. 2.界面搭建 背景图片(给控制器的view添加一个imageview,设置属性背景图片) 九个按钮(把九个按钮作为一个整体,使用一个大的view来管理这些小的view,这些小的view就是9个button.如果使

iOS开发UI篇—实现一个简单的手势解锁应用(完善)

iOS开发UI篇—实现一个简单的手势解锁应用(完善) 一.需要实现的效果 二.应用完善 1.绘制不处于按钮范围内的连线 2.解决bug(完善) bug1:如果在began方法中通知view绘图,那么会产生bug.因为,当前点没有清空,在手指移开之后要清空当前点.可以在绘制前进行判断,如果当前点是(0,0)那么就不划线.或者在began方法中不进行重绘. bug2:无限菊花.自定义view的背景色为默认的(黑色),只要重写了drawrect方法,view默认的背景颜色就是黑色的,因为上下文默认的颜

《简单之美》读后感(part1)

<简单之美>一书,对于软件开发的过程,在很多地方值得我们深思. 作者讲述了软件开发中各种常见问题,从思想层面深刻剖析,最后还是归结到以人为本这一核心思想.以人为本不是一句空话,核心就是对思想和文化的关注,软件是给人用的,如果抓不住以人为本这一核心思想,那软件注定是失败的. 本书传递的思想是,用简单的原则.富于想象的精神.文化的视角来认识软件开发. 软件的美和价值在于创造,创造的根源在于想象.当然这必须基于对软件开发的深刻理解.重点在于需要形成一个自己的,系统而且完整的观念.