master
潘啟华 6 years ago
parent 80f7b5dde6
commit cc37f4fd11
  1. 8
      db/src/main/java/db/config/HibernateConfig.java
  2. 4
      web/src/main/java/web/config/AbstractWebConfig.java
  3. 2
      web/src/main/java/web/config/AppConfig.java
  4. 17
      web/src/main/java/web/config/SpringConfig.java
  5. 13
      web/src/main/java/web/controller/BaseController.java
  6. 33
      web/src/main/java/web/controller/WordController.java
  7. 29
      web/src/main/java/web/filter/Filter.java
  8. 11
      web/src/main/java/web/service/BaseService.java
  9. 17
      web/src/main/java/web/service/BiliService.java
  10. 20
      web/src/main/webapp/WEB-INF/jsp/head.jsp
  11. 6
      web/src/main/webapp/WEB-INF/jsp/index.jsp
  12. 188
      web/src/main/webapp/WEB-INF/jsp/word/word.jsp
  13. 5
      web/src/test/java/spring/SpringMVCTest.java

@ -117,7 +117,8 @@ public class HibernateConfig {
* @return
*/
private HibernateTemplate initDB(DataSourceModel dataSourceModel) {
SessionFactory sessionFactory = initSessionFactory(dataSource(dataSourceModel), (LocalSessionFactoryBean bean) -> {
DruidDataSource dataSource=dataSource(dataSourceModel);
SessionFactory sessionFactory = initSessionFactory(dataSource, (LocalSessionFactoryBean bean) -> {
Class c;
try {
//按照规则拼接实体类注解标记全类名
@ -139,6 +140,8 @@ public class HibernateConfig {
if (sessionFactory != null) {
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory);
hibernateTransactionManager.setDataSource(dataSource);
hibernateTransactionManager.afterPropertiesSet();
//添加事务管理器
beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbId(),DBBeanNameManager.transactionManager),hibernateTransactionManager);
return new HibernateTemplate(sessionFactory);
@ -183,9 +186,8 @@ public class HibernateConfig {
for (DataSourceModel dataSourceModel : dataSourceModels) {
HibernateTemplate hibernateTemplate = initDB(dataSourceModel);
if (hibernateTemplate != null) {
//添加事务管理器
beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbId(),DBBeanNameManager.hibernateTemplate),hibernateTemplate);
beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbId(),DBBeanNameManager.hibernateTemplate),hibernateTemplate);
Class c;
try {

@ -3,6 +3,7 @@ package web.config;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import web.filter.Filter;
import javax.servlet.*;
import java.util.EnumSet;
@ -38,6 +39,9 @@ public class AbstractWebConfig extends AbstractAnnotationConfigDispatcherServlet
FilterRegistration.Dynamic characterEncodingFilter=super.registerServletFilter(servletContext,new CharacterEncodingFilter(encoding));
characterEncodingFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
FilterRegistration.Dynamic myfilter=super.registerServletFilter(servletContext,new Filter());
myfilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
ServletRegistration.Dynamic servlet=servletContext.addServlet("DruidStatView", StatViewServlet.class);
servlet.addMapping("/druid/*");

@ -5,11 +5,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement
@PropertySource("classpath:config.properties")
@Import(HibernateConfig.class)
public class AppConfig {

@ -1,14 +1,16 @@
package web.config;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import db.config.HibernateConfig;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.List;
@ -18,6 +20,7 @@ import java.util.List;
*/
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@PropertySource({"classpath:config.properties"})
@ComponentScan({"web.controller","web.service","web.util","web.aop","core.thrift"})
public class SpringConfig implements WebMvcConfigurer {
@ -34,14 +37,6 @@ public class SpringConfig implements WebMvcConfigurer {
"classpath:/META-INF/resources/webjars/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
HibernateConfig.get().forEach((key,hibernateTemplate)->{
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(hibernateTemplate.getSessionFactory());
registry.addWebRequestInterceptor(interceptor);
});
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

@ -51,12 +51,14 @@ public abstract class BaseController<T extends AbstractModel,A extends T,E exten
}
}
@ResponseBody
@RequestMapping(value = "C",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
public JsonResult save(T model){
JsonResult result=new JsonResult();
JsonResult<T> result=new JsonResult();
result.setAction(DBAction.C);
try {
service.save(model);
result.setData(model);
result.setType(Type.success);
} catch (DataAccessException e) {
e.printStackTrace();
@ -65,6 +67,7 @@ public abstract class BaseController<T extends AbstractModel,A extends T,E exten
return result;
}
@ResponseBody
@RequestMapping(value = "R",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.GET)
public JsonResult get(T model){
JsonResult<T> result=new JsonResult();
@ -94,12 +97,14 @@ public abstract class BaseController<T extends AbstractModel,A extends T,E exten
return result;
}
@ResponseBody
@RequestMapping(value = "U",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
public JsonResult update(T model){
JsonResult result=new JsonResult();
JsonResult<T> result=new JsonResult();
result.setAction(DBAction.U);
try {
service.update(model);
result.setData(model);
result.setType(Type.success);
} catch (DataAccessException e) {
e.printStackTrace();
@ -108,12 +113,14 @@ public abstract class BaseController<T extends AbstractModel,A extends T,E exten
return result;
}
@ResponseBody
@RequestMapping(value = "D",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
public JsonResult delete(T model){
JsonResult result=new JsonResult();
JsonResult<T> result=new JsonResult();
result.setAction(DBAction.D);
try {
service.delete(model);
result.setData(model);
result.setType(Type.success);
} catch (DataAccessException e) {
e.printStackTrace();

@ -1,11 +1,44 @@
package web.controller;
import db.model.bilibili.WordModel;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
@RequestMapping("/word")
public class WordController extends BiliController<WordModel> {
@Autowired
@Qualifier("Tweb.service.BiliService")
private HibernateTransactionManager hibernateTransactionManager;
@RequestMapping
public String list(@ModelAttribute WordModel queryCommand, @RequestParam(defaultValue = "0") int firstResult, @RequestParam(defaultValue = "0") int maxResults, Model model){
model.addAttribute("word",super.get(queryCommand, firstResult, maxResults));
List<String> courseNames=service.find(DetachedCriteria.forClass(WordModel.class).setProjection(Projections.groupProperty("courseName")));
model.addAttribute("courseNames",courseNames);
return "word/word";
}
@Override
protected DetachedCriteria getDetachedCriteria(WordModel queryCommand) {
if(StringUtils.isNotEmpty(queryCommand.getCourseName())){
return super.getDetachedCriteria(queryCommand).add(Restrictions.eq("courseName",queryCommand.getCourseName()));
}else{
return super.getDetachedCriteria(queryCommand);
}
}
}

@ -0,0 +1,29 @@
package web.filter;
import db.annotation.Aliyun;
import db.config.HibernateConfig;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
public class Filter extends OpenSessionInViewFilter {
@Override
protected SessionFactory lookupSessionFactory() {
return HibernateConfig.get(Aliyun.class).getSessionFactory();
}
@Override
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setHibernateFlushMode(FlushMode.AUTO);
return session;
} catch (HibernateException var3) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", var3);
}
}
}

@ -31,11 +31,11 @@ public abstract class BaseService{
return hibernateTemplate;
}
public final <T extends AbstractModel> Serializable save(T command) throws DataAccessException {
public <T extends AbstractModel> Serializable save(T command) throws DataAccessException {
return getHibernateTemplate().save(command);
}
public final <T extends AbstractModel> void update(T command) throws DataAccessException{
public <T extends AbstractModel> void update(T command) throws DataAccessException{
getHibernateTemplate().update(command);
}
@ -48,8 +48,11 @@ public abstract class BaseService{
}
}
public final <T extends AbstractModel> void delete(T command) throws DataAccessException{
getHibernateTemplate().delete(get(command));
public <T extends AbstractModel> void delete(T command) throws DataAccessException{
T model=get(command);
if(model!=null){
getHibernateTemplate().delete(model);
}
}
public final List find(DetachedCriteria criteria, int firstResult,int maxResults) throws DataAccessException{

@ -2,10 +2,27 @@ package web.service;
import db.annotation.Aliyun;
import db.annotation.Model;
import db.model.AbstractModel;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
@Service
@Model(Aliyun.class)
public class BiliService extends BaseService{
@Override
@Transactional(value = "Tweb.service.BiliService")
public <T extends AbstractModel> Serializable save(T command) throws DataAccessException {
return super.save(command);
}
@Override
@Transactional(value = "Tweb.service.BiliService")
public <T extends AbstractModel> void delete(T command) throws DataAccessException {
super.delete(command);
}
}

@ -30,6 +30,24 @@
<script src="/webjars/jquery-tmpl/beta1.0.0/jquery.tmpl.min.js"></script>
<script>
$.fn.serializeJson = function() {
var arr = this.serializeArray();
var json = {};
arr.forEach(function(item) {
var name = item.name;
var value = item.value;
if (!json[name]) {
json[name] = value;
} else if ($.isArray(json[name])) {
json[name].push(value);
} else {
json[name] = [json[name], value];
}
});
return json;
}
</script>
<![endif]-->

@ -66,14 +66,10 @@
<span id="navSpan"><b>Close</b>&nbsp;<i class="fas fa-angle-double-up"></i></span>
</button>
<div class="btn-group" aria-label="Basic example" id="tabs">
<div class="btn-group col-11 justify-content-center" id="tabs">
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</nav>
<div class="position-relative">

@ -0,0 +1,188 @@
<%--
Created by IntelliJ IDEA.
User: 潘啟华
Date: 2018/8/25
Time: 13:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!--输出,条件,迭代标签库-->
<html>
<head>
<title>Title</title>
<c:import url="../head.jsp"/>
<script id="demo" type="text/x-jquery-tmpl">
<a class="list-group-item list-group-item-action list-group-item-{{= type}} text-center" id="{{= id}}"><span>{{= chinese}}</span><span style="display:none">==============={{= kana}}</span><i class="fas fa-times"></i></a>
</script>
<script>
$(function () {
// $("#demo").tmpl([{type: 'primary'}, {type: 'secondary'}, {type: 'success'}, {type: 'danger'}, {type: 'warning'}, {type: 'info'}, {type: 'light'}, {type: 'dark'}]).appendTo('#word');
$("#myTab>li>a").click(function () {
if ($(this).attr('id') == 'add-tab') {
$("#add").show();
$("#add input").removeAttr("disabled");
$("button").show().text("添加")
if ($("select>option").length == 0) {
$("#customCheck1").click();
}
$("#customCheck1").parent().show()
} else {
$("#add").hide();
$("#add input").attr("disabled", "disabled");
$("button").text("查询");
$("input[name=courseName]").parent().hide();
if ($("select>option").length == 0) {
$("button").hide();
$("label[for=courseName]").text('没有任何课程');
$("select").hide();
} else {
$("label[for=courseName]").text('课程选择');
}
$("#customCheck1").parent().hide()
}
});
$("#word").on("click", 'a', function () {
if ($(this).find("span:last").is(":visible")) {
$(this).find("span:last").hide();
} else {
$(this).find("span:last").show();
}
});
$("#word").on("click","i",function () {
if(confirm('确认删除该单词?')) {
var id=$(this).parent().attr('id');
$.post('/word/D',{'id':id},function(result){
if (result['type'] == 'success') {
$('#'+id).remove();
}else{
alert('删除失败');
}
});
}
});
$("button").click(function () {
if ($("#search-tab").hasClass('active')) {
$("form").submit();
} else {
if ($('input[name=courseName]').is(":visible") && $('input[name=courseName]').val() == '') {
alert('请输入课程名');
return;
}
if ($('#kana').val() == '') {
alert('请输入假名');
return;
}
if ($('#chinese').val() == '') {
alert('请输入中文名');
return;
}
$.post('/word/C', $('form').serializeJson(), function (result) {
console.info(result);
if (result['type'] == 'success') {
result['data']['type'] = 'primary';
$("#demo").tmpl(result['data']).appendTo('#word');
} else {
alert('添加失败');
}
});
}
});
<c:forEach items="${word.data}" var="i">
$("#demo").tmpl({'id':${i.id},'type': 'primary', 'kana': '${i.kana}', 'chinese': '${i.chinese}'}).appendTo('#word');
</c:forEach>
$("#customCheck1").click(function () {
if ($(this).is(":checked")) {
$("select[name=courseName]").parent().hide();
$("input[name=courseName]").parent().show();
$("label[for=courseName]").text('课程名');
$("select[name=courseName]").attr("disabled", "disabled");
$("input[name=courseName]").removeAttr("disabled")
} else {
$("select[name=courseName]").parent().show();
$("input[name=courseName]").parent().hide();
$("label[for=courseName]").text('课程选择');
$("input[name=courseName]").attr("disabled", "disabled");
$("select[name=courseName]").removeAttr("disabled")
}
});
});
</script>
</head>
<body>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" id="search-tab">查询</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" id="add-tab">添加</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<form:form modelAttribute="wordModel">
<div class="form-group row justify-content-center">
<label for="courseName" class="col-1">${empty courseNames?'没有任何课程':'课程选择'}</label>
<div class="col-2" <c:if test="${empty courseNames}">style="display: none"</c:if>>
<select name="courseName" <c:if test="${empty courseNames}">disabled="disabled"</c:if>>
<c:forEach items="${courseNames}" var="courseName">
<option value="${courseName}"
<c:if test="${wordModel.courseName==courseName}">selected</c:if>>${courseName}</option>
</c:forEach>
</select>
</div>
<div class="col-2" style="display: none">
<input name="courseName" <c:if test="${!empty courseNames}">disabled="disabled"</c:if>>
</div>
<div class="col-1" style="display: none">
<input type="checkbox" class="custom-control-input"
<c:if test="${empty courseNames}">checked</c:if> id="customCheck1">
<label class="custom-control-label" for="customCheck1">新建课程</label>
</div>
</div>
<div id="add" style="display: none">
<div class="form-group row justify-content-center">
<label for="kana" class="col-1">假名</label>
<div class="col-3">
<form:input path="kana"/>
</div>
</div>
<div class="form-group row justify-content-center">
<label for="chinese" class="col-1">中文</label>
<div class="col-3">
<form:input path="chinese"/>
</div>
</div>
</div>
<div class="form-group row">
<button type="button" class="btn btn-primary offset-5"
<c:if test="${empty courseNames}">style="display: none"</c:if>>查询
</button>
</div>
</form:form>
</div>
<div id="word">
</div>
</body>
</html>

@ -53,6 +53,7 @@ public class SpringMVCTest {
@Test
@Transactional
@Rollback(false)
public void save() throws Exception {
ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/word/C").param("courseName","123").param("kana","456").param("chinese","789"));
resultActions.andDo(MockMvcResultHandlers.print()).andReturn();
@ -62,7 +63,7 @@ public class SpringMVCTest {
@Transactional
@Rollback(false)
public void update() throws Exception{
ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/word/U").param("id","1").param("courseName","123").param("kana","666").param("chinese","666"));
ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/word/U").param("id","2").param("courseName","123").param("kana","666").param("chinese","666"));
resultActions.andDo(MockMvcResultHandlers.print()).andReturn();
}
@ -71,7 +72,7 @@ public class SpringMVCTest {
@Transactional
@Rollback(false)
public void delete() throws Exception{
ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/word/D").param("id","1"));
ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/word/D").param("id","2"));
resultActions.andDo(MockMvcResultHandlers.print()).andReturn();
}

Loading…
Cancel
Save