博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javaweb各种框架组合案例(一):maven+spring+springMVC+jdbcTemplate
阅读量:5836 次
发布时间:2019-06-18

本文共 15212 字,大约阅读时间需要 50 分钟。

为了体现spring jdbc对于单表操作的优势,我专门对dao层做了一个抽离,使得抽离出的核心dao具有通用性。主要技术难点是对于泛型的反射。注意:单表操作中,数据库表的字段要和实体类的属性名保持高度一致,否则可能会出错。

1.整体项目结构

 

2.pom.xml

4.0.0
com.xiaog
music4j
0.0.1-SNAPSHOT
war
UTF-8
4.2.2.RELEASE
5.1.29
3.0-alpha-1
1.8.1
1.9
1.4
5.0.2.Final
8.1.8.v20121106
1.7.5
6.8.7
1.7
1.7
junit
junit
4.11
test
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-webmvc
${spring.version}
commons-dbcp
commons-dbcp
${commons-dbcp.version}
mysql
mysql-connector-java
${mysql.version}
javax.servlet
servlet-api
${servlet.version}
provided
org.aspectj
aspectjweaver
${aspectj.version}
org.testng
testng
${testng.version}
test
org.springframework
spring-test
${spring.version}
test
jstl
jstl
1.1.2
ch.qos.logback
logback-classic
1.2.3
ch.qos.logback
logback-core
1.2.3
org.logback-extensions
logback-ext-spring
0.1.4
org.slf4j
slf4j-api
1.7.25
org.slf4j
jcl-over-slf4j
1.7.25
compile
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
UTF-8
org.apache.tomcat.maven
tomcat7-maven-plugin
2.1
9999
/music4j
UTF-8
music4j
tomcat7

 

 

3.各配置文件

(1)spring-context.xml

 

 

(2)spring-mvc.xml

 

 

(3)logback.xml

UTF-8
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

 

 

(4)web.xml

music4j
contextConfigLocation
classpath:spring-context.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
spring-mvc
/
logbackConfigLocation
classpath:logback.xml
ch.qos.logback.ext.spring.web.LogbackConfigListener
index.jsp

 

 

4.数据库

create database ssjdbc;//创建ssjdbc数据库//创建user表CREATE TABLE `user` (   `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(32) DEFAULT NULL,  `password` varchar(32) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;//插入数据3条insert into user(username,password) values (1001,123),(1002,456),(1003,789);

 

5.编写工具类SqlFactory,用于生成动态sql语句,类似mybatis的动态sql语句

package com.music4j.util;import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class SqlFactory {    private String tableName;        public Object[] params;        public SqlFactory(Class
clazz) { tableName = clazz.getSimpleName().toLowerCase(); } private final static Logger logger = LoggerFactory.getLogger(SqlFactory.class); private Map
objectToMap(Object entity) { Field[] fields = entity.getClass().getDeclaredFields(); Map
map = new HashMap
(); for(Field field : fields) { field.setAccessible(true);//设置属性可访问 Object value = null; try { value = field.get(entity); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } if(value != null) { map.put(field.getName(), value); } } return map; } public String getDeleteSql() { StringBuilder sql = new StringBuilder("delete from ").append(tableName).append(" where id = ?"); logger.info(sql.toString()); return sql.toString(); } public String getSelectOneSql() { StringBuilder sql = new StringBuilder("select * from ").append(tableName).append(" where id = ?"); logger.info(sql.toString()); return sql.toString(); } public String getInsertSql(Object entity) { Map
map = this.objectToMap(entity); map.remove("id"); params = new Object[map.size()]; StringBuilder stringBuiler = new StringBuilder("insert into ").append(tableName).append("("); for(String key : map.keySet()) { stringBuiler.append(key).append(","); } stringBuiler.deleteCharAt(stringBuiler.length()-1).append(") values ("); int i = 0; for(String key : map.keySet()) { stringBuiler.append("?,"); params[i] = map.get(key); i++; } stringBuiler.deleteCharAt(stringBuiler.length()-1).append(")"); map = null; logger.info(stringBuiler.toString()); return stringBuiler.toString(); } public String getUpdateSql(Object entity) { Map
map = this.objectToMap(entity); params = new Object[map.size()]; params[params.length-1] = map.remove("id"); StringBuilder stringBuiler = new StringBuilder("update ").append(tableName).append(" set "); int i = 0; for(String key : map.keySet()) { stringBuiler.append(key).append("=?,"); params[i] = map.get(key); i++; } stringBuiler.deleteCharAt(stringBuiler.length()-1).append(" where id = ?"); map = null; logger.info(stringBuiler.toString()); return stringBuiler.toString(); } public String getSelectList(Object entity) { Map
map = this.objectToMap(entity); map.remove("id"); params = new Object[map.size()]; StringBuilder stringBuiler = new StringBuilder("select * from ").append(tableName).append(" where "); int i = 0; for(String key : map.keySet()) { stringBuiler.append(key).append("=? and "); params[i] = map.get(key); i++; } stringBuiler.delete(stringBuiler.length()-4, stringBuiler.length()); map = null; logger.info(stringBuiler.toString()); return stringBuiler.toString(); }}

 

 

6.编写核心dao接口及其实现类

package com.music4j.core.dao;import java.util.List;public interface CoreDao
{ int insert(T t); int delete(int id); int update(T t); T getOne(int id); List
getList(T t);}
package com.music4j.core.dao.impl;import java.lang.reflect.ParameterizedType;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import com.music4j.core.dao.CoreDao;import com.music4j.util.SqlFactory;public class CoreDaoImpl
implements CoreDao
{ @Autowired private JdbcTemplate jdbcTemplate; private SqlFactory sqlFactory; private Class
clazz; @SuppressWarnings("unchecked") public CoreDaoImpl() { this.clazz = (Class
)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; sqlFactory = new SqlFactory(this.clazz); } @Override public int insert(T t) { return jdbcTemplate.update(sqlFactory.getInsertSql(t),sqlFactory.params); } @Override public int delete(int id) { return jdbcTemplate.update(sqlFactory.getDeleteSql(),id); } @Override public int update(T t) { return jdbcTemplate.update(sqlFactory.getUpdateSql(t),sqlFactory.params); } @Override public T getOne(int id) { return jdbcTemplate.queryForObject(sqlFactory.getSelectOneSql(), new BeanPropertyRowMapper
(clazz),id); } @Override public List
getList(T t) { return jdbcTemplate.query(sqlFactory.getSelectList(t),new BeanPropertyRowMapper
(clazz),sqlFactory.params); }}

 

 

7.编写实体类dao接口及其实现,因为已经有了核心接口和实现,所以只需继承即可

package com.music4j.dao;import com.music4j.core.dao.CoreDao;import com.music4j.entity.User;public interface UserDao extends CoreDao
{}
package com.music4j.dao.impl;import org.springframework.stereotype.Repository;import com.music4j.core.dao.impl.CoreDaoImpl;import com.music4j.dao.UserDao;import com.music4j.entity.User;@Repositorypublic class UserDaoImpl extends CoreDaoImpl
implements UserDao {}

 

 

8.编写service接口及其实现

package com.music4j.service;import com.music4j.entity.User;public interface UserService {    User login(User user);}
package com.music4j.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.music4j.dao.UserDao;import com.music4j.entity.User;import com.music4j.service.UserService;@Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserDao userDao;        @Override    public User login(User user) {        List
users = userDao.getList(user); if(users!=null&&users.size()>0) { return users.get(0); }else { return null; } }}

 

 

9.编写controller

package com.music4j.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.music4j.entity.User;import com.music4j.service.UserService;@Controller@RequestMapping("/user")public class UserController {        @Autowired    private UserService userService;        @RequestMapping(value = "/login",params= {"username","password","username!=","password!="})    public String login(Model model,User user) {        user = userService.login(user);        System.out.println("user="+user);        model.addAttribute("user", user);        return "result";    }    }

 

 

10.编写jsp页面测试登录

(1)index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Insert title here

 

 

(2)result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
username=${user}

 

转载于:https://www.cnblogs.com/xiaogblog/p/11052544.html

你可能感兴趣的文章
Kconfig的格式
查看>>
关于Cursor的moveToFirst和moveToNext的意义
查看>>
个人--工资划分5份
查看>>
有关文件下载的文件名
查看>>
史上最详细的wamp配置虚拟域名步骤
查看>>
oracle 授权
查看>>
lv扩展磁盘空间
查看>>
java8之stream流的基本操作
查看>>
二维数组计算协方差java
查看>>
SpringBoot下Redis相关配置是如何被初始化的
查看>>
为你的AliOS Things应用增加自定义cli命令
查看>>
MongoDB 创建基础索引、组合索引、唯一索引以及优化
查看>>
百度PaddlePaddle常规赛NLP赛道火热开启
查看>>
稳了!这才是cookie,session与token的真正区别
查看>>
python项目实战:制作一个简易的GUI界面浏览器
查看>>
OSChina 周二乱弹 —— 假期余额已不足!
查看>>
前端那些事之React篇--helloword
查看>>
Oracle11g及PL/SQL Developer的安装和配置
查看>>
ios的google解析XML框架GDataXML的配置及使用
查看>>
netty-当一个客户端连接到来的时候发生了什么
查看>>