sts + gradle 搭建無XML SSH環境

參考資料

SpringMVC3.1+Hibernate4.1.7徹底基於註解配置(零配置文件)javascript

SpringMVC4零配置html

Java EE開發的顛覆者 Spring Boot 實戰java

說明

spring mvc 的配置參考的 Java EE開發的顛覆者 Spring Boot 實戰 與 SpringMVC4零配置,集成hibernate參考自 SpringMVC3.1+Hibernate4.1.7徹底基於註解配置(零配置文件)mysql

iteye的代碼示例很不錯,因此我把他的代碼放到了個人git@osc上,地址:springboot-study,一樣也有我本篇博客的全部代碼,在spring4-mvc項目中。jquery

要注意:git

  • 數據庫表要本身手動建立
  • tomcat最好是8.0及以上
  • spring 最好是4.1.X及以上,個人是4.1.9,這主要是爲了之後的spring boot
  • 項目全部文件列表以下:

 spring4-mvc 項目文件列表

環境:

os : windowsweb

ide : stsspring-tool-suite-3.7.3.RELEASE-e4.5.2-win32-x86_64ajax

jdk : 1 .7.0_79spring

tomcat : 8.0.36sql

gradle : 2.7

database : mysql

環境搭建

關於怎樣用gradle搭建spring mvc 項目,我已在上一篇博客中寫明:sts + gradle + tomcat 運行 spring mvc

代碼

數據庫文件:

spring4mvc.sql

/*
Navicat MariaDB Data Transfer

Source Server         : localhost
Source Server Version : 100113
Source Host           : localhost:3306
Source Database       : spring4mvc

Target Server Type    : MariaDB
Target Server Version : 100113
File Encoding         : 65001

Date: 2016-08-04 01:29:50
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for book_type
-- ----------------------------
DROP TABLE IF EXISTS `book_type`;
CREATE TABLE `book_type` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type_name` varchar(100) NOT NULL,
  `type_desc` varchar(255) DEFAULT '',
  `type_family` varchar(5) DEFAULT NULL,
  `type_valid` tinyint(1) NOT NULL,
  `version` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `type_name` (`type_name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of book_type
-- ----------------------------
INSERT INTO `book_type` VALUES ('1', '計算機', '教育', '-', '1', '1');

配置文件

標題寫的是無XML,可是隻是說沒有了spring的配置文件與web.xml,這已經能省很大的功夫了。一行配置都沒有的項目我以爲很差

build.gradle

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jetty'


// JDK 7
sourceCompatibility = 1.7
targetCompatibility = 1.7

repositories {
	mavenLocal()
    mavenCentral()
    jcenter()
}


String javaeeVersion = '7.0'
String servletVersion = '3.1.0'
String jstlVersion = '1.2'
  
String springVersion = '4.1.9.RELEASE'
String hibernateVersion = '4.2.21.Final'
String aspectjVersion = '1.8.5'
 

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    
    // j2ee base
	//providedCompile ( 'javax:javaee-web-api:' + javaeeVersion )
    
	providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
    compile 'javax.servlet:jstl:1.2'
    
    // spring
    compile ('org.springframework:spring-context:' + springVersion)  
    compile ('org.springframework:spring-oxm:' + springVersion)  
    compile ('org.springframework:spring-tx:' + springVersion)  
    compile ('org.springframework:spring-jdbc:' + springVersion)  
    compile ('org.springframework:spring-beans:' + springVersion)  
    compile ('org.springframework:spring-aop:' + springVersion)  
    compile ('org.springframework:spring-test:' + springVersion)  
    compile ('org.springframework:spring-aspects:' + springVersion)  
    compile ('org.springframework:spring-web:' + springVersion)  
    compile ('org.springframework:spring-core:' + springVersion)  
    compile ('org.springframework:spring-webmvc:' + springVersion)
    
    // aspectj
	compile ( 'org.aspectj:aspectjrt:' + aspectjVersion )
	compile ( 'org.aspectj:aspectjweaver:' + aspectjVersion )
    
    // mysql
    compile ('mysql:mysql-connector-java:5.1.30')
    compile ('com.mchange:c3p0:0.9.2')
    
    // hibernate
    compile ('org.hibernate:hibernate-core:' + hibernateVersion)
    compile ('org.hibernate:hibernate-entitymanager:' + hibernateVersion)
    compile ('org.springframework:spring-orm:' + springVersion)
    
    // json
    compile ('org.codehaus.jackson:jackson-mapper-asl:1.9.13' )
    compile ('com.google.code.gson:gson:2.2.2' )
    
    
    // logback
    compile ('org.slf4j:jcl-over-slf4j:1.7.12')
    compile ('ch.qos.logback:logback-classic:1.1.3')
    compile ('org.logback-extensions:logback-ext-spring:0.1.2')

	//test
    testCompile 'junit:junit:4.12'
}

jettyRun {
	httpPort = 8080
	contextPath = 'spring4-mvc'
}

//tasks.withType(Compile) {  
//    options.encoding = "UTF-8"  
//}

db.properties

這個文件沒有起做用,不知道怎麼回事,我暫時把數據庫鏈接的信息寫在了配置代碼中

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring4mvc?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

logback.xml

這裏要注意日誌的路徑最好用絕對路徑

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑 -->
	<property name="LOG_HOME" value="d:/logs/spring4-mvc" />
	<!-- 控制檯輸出 -->
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<!-- 日誌輸出編碼 -->
		<Encoding>UTF-8</Encoding>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
				%msg%n
			</pattern>
		</layout>
	</appender>
	<!-- 按照天天生成日誌文件 -->
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<Encoding>UTF-8</Encoding>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日誌文件輸出的文件名 -->
			<FileNamePattern>${LOG_HOME}/ssh.log.%d{yyyy-MM-dd}.log
			</FileNamePattern>
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
				%msg%n
			</pattern>
		</layout>
		<!--日誌文件最大的大小 -->
		<triggeringPolicy
			class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<MaxFileSize>10MB</MaxFileSize>
		</triggeringPolicy>
	</appender>
	<!-- show parameters for hibernate sql 專爲 Hibernate 定製 -->
	<logger name="org.hibernate.type.descriptor.sql.BasicBinder"
		level="TRACE" />
	<logger name="org.hibernate.type.descriptor.sql.BasicExtractor"
		level="DEBUG" />
	<logger name="org.hibernate.SQL" level="DEBUG" />
	<logger name="org.hibernate.type" level="TRACE" />
	<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
	<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />

	<!-- 日誌輸出級別 -->
	<root level="INFO">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
	</root>

	<!--日誌異步到數據庫 -->
	<!-- <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource 
		class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <dataSource 
		class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> 
		<url>jdbc:mysql://127.0.0.1:3306/databaseName</url> <user>root</user> <password>root</password> 
		</dataSource> </connectionSource> </appender> -->
</configuration>

純java配置取代XML配置

個人配置全放在 com.laolang.ssh.config 中

DataSourceConfig

package com.laolang.ssh.config;

import java.beans.PropertyVetoException;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

import com.mchange.v2.c3p0.ComboPooledDataSource;


/**
 * 數據源和Hibernate配置
 * 
 * @author 小代碼
 *
 */
@Configuration
@PropertySource("classpath:db.properties")
public class DataSourceConfig {

	@Bean
	public DataSource dataSource() throws PropertyVetoException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(userName);
		dataSource.setPassword(passWord);
		dataSource.setJdbcUrl(url);
		dataSource.setDriverClass(driverClass);
		return dataSource;

	}

	@Bean
	public LocalSessionFactoryBean sessionFactory() throws PropertyVetoException {
		LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource());
		Properties properties = new Properties();
		properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
		properties.setProperty("hibernate.show_sql", "true");
		properties.setProperty("format_sql", "true");
		properties.setProperty("hibernate.hbm2ddl.auto.show_sql", "update");
		sessionFactoryBean.setHibernateProperties(properties);
		sessionFactoryBean.setPackagesToScan("com.laolang.ssh.domain");

		return sessionFactoryBean;
	}

	@Bean
	public HibernateTransactionManager txManager() throws PropertyVetoException {
		HibernateTransactionManager txManager = new HibernateTransactionManager();
		txManager.setSessionFactory(sessionFactory().getObject());
		return txManager;
	}

	public String getDriverClass() {
		return driverClass;
	}

	public void setDriverClass(String driverClass) {
		this.driverClass = driverClass;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	@Value("com.mysql.jdbc.Driver")
	private String driverClass;
	@Value("jdbc:mysql://localhost:3306/spring4mvc?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true")
	private String url;
	@Value("root")
	private String userName;
	@Value("root")
	private String passWord;

}

MyMvcConfig.java

package com.laolang.ssh.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * spring mvc 配置類
 * 
 * @author 小代碼
 * @version 1.0
 *
 */
@Configuration
@Import(DataSourceConfig.class)
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.laolang.ssh.*")
public class MyMvcConfig extends WebMvcConfigurationSupport {

	/**
	 * 視圖處理器
	 * 
	 */
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
	@Bean
	public HandlerMapping resourceHandlerMapping() {
    	return super.resourceHandlerMapping();
    }

	/**
	 * 資源訪問處理器
	 */
	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
	}
	
	
}

WebInitializer

package com.laolang.ssh.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * web配置,取代web.xml
 * @author Administrator
 *
 */
public class WebInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(MyMvcConfig.class);
		context.setServletContext(servletContext);
		
		Dynamic servlet = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
		servlet.addMapping("/");
		servlet.setLoadOnStartup(1);
	}

}

實體類

BookType.java

package com.laolang.ssh.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;


@Entity
@Table(name="book_type")
public class BookType implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public BookType() {
		super();
	}

	public BookType(String typeName, String typeDesc, String typeFamily, boolean typeValid) {
		super();
		this.typeName = typeName;
		this.typeDesc = typeDesc;
		this.typeFamily = typeFamily;
		this.typeValid = typeValid;
	}

	@Override
	public String toString() {
		return "BookType [id=" + id + ", typeName=" + typeName + ", typeDesc=" + typeDesc + ", typeFamily=" + typeFamily + ", typeValid=" + typeValid
				+ ", version=" + version + "]";
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTypeName() {
		return typeName;
	}

	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}

	public String getTypeDesc() {
		return typeDesc;
	}

	public void setTypeDesc(String typeDesc) {
		this.typeDesc = typeDesc;
	}

	public String getTypeFamily() {
		return typeFamily;
	}

	public void setTypeFamily(String typeFamily) {
		this.typeFamily = typeFamily;
	}

	public boolean isTypeValid() {
		return typeValid;
	}

	public void setTypeValid(boolean typeValid) {
		this.typeValid = typeValid;
	}

	public Integer getVersion() {
		return version;
	}

	public void setVersion(Integer version) {
		this.version = version;
	}

	@Id
	@GeneratedValue
	private Integer id;

	@Column(name="type_name",unique=true)
	private String typeName;

	@Column(name="type_desc")
	private String typeDesc;

	@Column(name="type_family")
	private String typeFamily;

	@Column(name="type_valid")
	private boolean typeValid;

	@Version
	private Integer version;

}

持久化操做

這一部分參考自 51cto 上的視頻 EasyUI+S2SH+MySQL 在線商城系統_上 [精講大項目],iteye那篇博客中提供的封裝我以爲更好。不過我打算之後用jpa,就先這麼的吧

BaseService

package com.laolang.ssh.service;


import java.util.List;

/**
 * 基本CRUD接口
 * 
 * @author 小代碼
 * @version 1.0
 *
 * @param <T>
 *            須要持久化的實體類
 */
public interface BaseService<T> {

	/**
	 * 保存
	 *
	 * @param t
	 *            實體類
	 */
	public void save(T t);

	/**
	 * 更新
	 *
	 * @param t
	 *            實體類
	 */
	public void merge(T t);

	/**
	 * 根據ID刪除
	 *
	 * @param id
	 *            要刪除的實體類的ID
	 */
	public void delete(Integer id);

	/**
	 * 經過ID查詢
	 *
	 * @param id
	 *            要查詢的實體的ID
	 * @return 查詢到的實體類,若是未查詢到,則返回null
	 */
	public T findById(Integer id);

	/**
	 * 查詢全部
	 *
	 * @return 查詢到的實體列表
	 */
	public List<T> findAll();

	/**
	 * 查詢全部
	 *
	 * @param firstResult
	 *            第幾頁
	 * @param maxResults
	 *            每頁記錄數
	 * @return 查詢到的實體列表
	 */
	public List<T> findAll(int firstResult, int maxResults);

	/**
	 * 系統記錄數
	 *
	 * @return 記錄數
	 */
	public Long findcount();

	/**
	 * 根據每頁記錄數,計算共有多少頁
	 *
	 * @param size
	 *            每頁記錄數
	 * @return 頁數
	 */
	public Long findpages(Integer size);
}

BaseServiceImpl

package com.laolang.ssh.service.impl;


import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laolang.ssh.service.BaseService;


@Transactional
@Service("baseService")
@Lazy(true)
@SuppressWarnings("unchecked")
public class BaseServiceImpl<T> implements BaseService<T> {

	@SuppressWarnings("rawtypes")
	public BaseServiceImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	@SuppressWarnings("rawtypes")
	private Class clazz;

	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public void save(T t) {
		getSession().save(t);

	}

	public void merge(T t) {
		getSession().merge(t);

	}

	public void delete(Integer id) {
		String hql = "DELETE " + clazz.getSimpleName() + " WHERE id=:id";
		getSession().createQuery(hql).setParameter("id", id).executeUpdate();

	}

	public T findById(Integer id) {
		String hql = "SELECT o FROM " + clazz.getSimpleName() + " o WHERE o.id=:id";
		return (T) getSession().createQuery(hql).setParameter("id", id).uniqueResult();
	}

	public List<T> findAll() {
		String hql = "FROM " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

	public List<T> findAll(int firstResult, int maxResults) {
		String hql = "FROM " + clazz.getSimpleName();
		firstResult = ( firstResult - 1 ) * maxResults;
		return getSession().createQuery(hql).setFirstResult(firstResult).setMaxResults(maxResults).list();
	}

	public Long findcount() {
		String hql = "SELECT COUNT(o) FROM " + clazz.getSimpleName() + " o";
		return (Long) getSession().createQuery(hql).uniqueResult();
	}

	public Long findpages(Integer size) {
		long count = findcount();
		long pages = count / size;
		if ((count - pages * size) > 0) {
			pages += 1;
		}
		return pages;
	}

}

BookTypeService

package com.laolang.ssh.service;

import com.laolang.ssh.domain.BookType;

public interface BookTypeService extends BaseService<BookType>{

}

BookTypeServiceImpl

package com.laolang.ssh.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laolang.ssh.domain.BookType;
import com.laolang.ssh.service.BookTypeService;


@Transactional
@Service("bookTypeService")
public class BookTypeServiceImpl extends BaseServiceImpl<BookType> implements BookTypeService {

}

controller

這個很簡單,沒什麼好說的

IndexController

package com.laolang.ssh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * 首頁處理器,在訪問首頁時,作初始化工做,如初始化顯示的類別
 * 
 * @author 小代碼
 * @version 1.0
 *
 */
@Controller
public class IndexController {

	@RequestMapping(value={"/"},method=RequestMethod.HEAD,produces="text/html")
	public String head(){
		return "index";
	}
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/","index"},method=RequestMethod.GET,produces="text/html")
	public String index( Model model ){
		model.addAttribute("msg", "Hello SpringMVC!");
		return "index";
	}
}

BookTypeController

package com.laolang.ssh.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestMethod;

import com.laolang.ssh.config.DataSourceConfig;
import com.laolang.ssh.domain.BookType;
import com.laolang.ssh.service.BookTypeService;

@Controller
@RequestMapping("/booktypes")
public class BookTypeController {
	
	Logger log = LoggerFactory.getLogger(BookTypeController.class);
	
	@Autowired
	private DataSourceConfig dataSourceConfig;
	
	@Autowired
	private BookTypeService bookTypeService;
	
	
	@RequestMapping(value="booktypes",method=RequestMethod.GET,produces="text/html")
	public String booktypes( Model model ){
		log.info("加載圖書類別列表");
		System.out.println(dataSourceConfig.getDriverClass());
		System.out.println(dataSourceConfig.getPassWord());
		System.out.println(dataSourceConfig.getUrl());
		System.out.println(dataSourceConfig.getUserName());
		
//		BookType bookType = new BookType("教育", "教育", "-", true);
		BookType bookType = new BookType();
		bookType = bookTypeService.findById(1);
		bookType.setTypeName("計算機");
		bookTypeService.merge(bookType);
		System.out.println(bookType.toString());
		model.addAttribute("bookType", bookType);
		return "booktype/booktypes";
	}

}

jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>

index
<br />
msg:${msg }
<br />

<a href="<%=path %>/booktypes/booktypes">booktypes</a>

<script type="text/javascript">

</script>
</body>
</html>

booktypes

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>booktypes</title>

<script type="text/javascript" src="<%=path %>/assets/js/jquery.min.js"></script>

</head>
<body>
typeName:${bookType.typeName }
<br />
typeName:${bookType.typeDesc }
<br />
typeFamily:${bookType.typeFamily }
<br />
typeValid:${bookType.typeValid }
<br />
成功!
<br />
<button id="jsonTest">json</button>


<script type="text/javascript">

$(function(){
	console.info('jquery 測試!');
});

$(function(){
	$('#jsonTest').click(function(){
		$.ajax({
			type : 'post',
			url : '<%=path %>/v1/booktypes',
			cache : false,
			dataType : 'json',
			success : function(data) {
				console.info(data);
			}
		});
	});
})
</script>

</body>
</html>

json 相關

  • pojo

ResltPojo

package com.laolang.ssh.v1.pojo;

import com.google.gson.annotations.SerializedName;

public class ResultPojo {
	
	public static final  Integer SUCCESS = 0;
	public static final  Integer FAILED = -1;


	
	
	public ResultPojo() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ResultPojo(Integer resultCode) {
		this.resultCode = resultCode;
		if( SUCCESS == resultCode ){
			this.resultDesc = "成功獲取!";
		}
		if( FAILED == resultCode ){
			this.resultDesc = "獲取失敗!";
		}
	}

	@Override
	public String toString() {
		return "ResultPojo [resultCode=" + resultCode + ", resultDesc=" + resultDesc + "]";
	}

	public Integer getResultCode() {
		return resultCode;
	}

	public void setResultCode(Integer resultCode) {
		this.resultCode = resultCode;
	}

	public String getResultDesc() {
		return resultDesc;
	}

	public void setResultDesc(String resultDesc) {
		this.resultDesc = resultDesc;
	}

	@SerializedName("resultCode")
	private Integer resultCode;

	@SerializedName("resultDesc")
	private String resultDesc;

}

BookTypePojo

package com.laolang.ssh.v1.pojo;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.annotations.SerializedName;
import com.laolang.ssh.domain.BookType;

public class BookTypePojo {

	public BookTypePojo() {
		super();
	}

	public BookTypePojo(BookType bookType) {
		this.id = bookType.getId();
		this.typeName = bookType.getTypeName();
		this.typeDesc = bookType.getTypeDesc();
		this.typeFamily = bookType.getTypeFamily();
		this.typeValid = bookType.isTypeValid();
	}

	public static List<BookTypePojo> getBookTypePojos(List<BookType> bookTypes) {
		List<BookTypePojo> bookTypePojos = new ArrayList<BookTypePojo>();
		if (bookTypes.size() > 0) {
			for (BookType bookType : bookTypes) {
				bookTypePojos.add(new BookTypePojo(bookType));
			}
		}
		return bookTypePojos;
	}

	@Override
	public String toString() {
		return "BookTypePojo [id=" + id + ", typeName=" + typeName + ", typeDesc=" + typeDesc + ", typeFamily=" + typeFamily + ", typeValid="
				+ typeValid + "]";
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTypeName() {
		return typeName;
	}

	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}

	public String getTypeDesc() {
		return typeDesc;
	}

	public void setTypeDesc(String typeDesc) {
		this.typeDesc = typeDesc;
	}

	public String getTypeFamily() {
		return typeFamily;
	}

	public void setTypeFamily(String typeFamily) {
		this.typeFamily = typeFamily;
	}

	public boolean isTypeValid() {
		return typeValid;
	}

	public void setTypeValid(boolean typeValid) {
		this.typeValid = typeValid;
	}

	@SerializedName("id")
	private Integer id;

	@SerializedName("typeName")
	private String typeName;

	@SerializedName("typeDesc")
	private String typeDesc;

	@SerializedName("typeFamily")
	private String typeFamily;

	@SerializedName("typeValid")
	private boolean typeValid;

}

BookTypeResultPojo

package com.laolang.ssh.v1.pojo;

import java.util.List;

import com.google.gson.annotations.SerializedName;
import com.laolang.ssh.domain.BookType;

public class BookTypeResultPojo {

	public BookTypeResultPojo() {
		super();
	}

	public BookTypeResultPojo(Integer resultCode, List<BookType> bookTypes) {
		this.result = new ResultPojo(resultCode);
		this.bookTypePojos = BookTypePojo.getBookTypePojos(bookTypes);
	}

	@Override
	public String toString() {
		return "BookTypeResultPojo [result=" + result + ", bookTypePojos=" + bookTypePojos + "]";
	}

	public ResultPojo getResult() {
		return result;
	}

	public void setResult(ResultPojo result) {
		this.result = result;
	}

	public List<BookTypePojo> getBookTypePojos() {
		return bookTypePojos;
	}

	public void setBookTypePojos(List<BookTypePojo> bookTypePojos) {
		this.bookTypePojos = bookTypePojos;
	}

	@SerializedName("result")
	private ResultPojo result;

	@SerializedName("bookTypePojos")
	private List<BookTypePojo> bookTypePojos;

}
  • JsonUtil

JsonUtil

package com.laolang.ssh.util;

import com.google.gson.Gson;
import com.google.gson.JsonNull;

public class JsonUtil {
	
	public static final Gson gson = new Gson();
	
	public static String toJson( Object o ){
		if( null == o ){
			return gson.toJson(JsonNull.INSTANCE);
		}
		return gson.toJson(o);
	}

}
  • v1/controller

BookTypesController

package com.laolang.ssh.v1.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.laolang.ssh.domain.BookType;
import com.laolang.ssh.service.BookTypeService;
import com.laolang.ssh.util.JsonUtil;
import com.laolang.ssh.v1.pojo.BookTypeResultPojo;
import com.laolang.ssh.v1.pojo.ResultPojo;

@Controller
@RequestMapping("/v1/booktypes")
public class BookTypesController {
	
	Logger log = LoggerFactory.getLogger(BookTypesController.class);
	
	@Autowired
	private BookTypeService bookTypeService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/json")
	public String BookTypeList(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size, Model model, HttpSession session, HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		log.info("發送圖書類別信息");

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		String jsonStr;
		
		
		Integer firstResult = null == page ? 1 : page;
		Integer maxResults = null == size ? 10 : size;
		List<BookType> bookTypes = bookTypeService.findAll(firstResult, maxResults);
		BookTypeResultPojo bookTypeResultPojo ;
		if( bookTypes.size() > 0 ){
			bookTypeResultPojo = new BookTypeResultPojo(ResultPojo.SUCCESS, bookTypes);
		}else{
			bookTypeResultPojo = new BookTypeResultPojo(ResultPojo.FAILED, bookTypes);
		}
		jsonStr = JsonUtil.toJson( bookTypeResultPojo );
		out.print(jsonStr);
		out.flush();
		out.close();
		return null;
	}

}

結語

最後的運行效果圖就再也不貼了。還有文件上傳、下載,輸出圖片什麼的,查一下資料應該不是太大問題,並且我這個項目應該會長期寫下去,做爲之後建立新項目的藍本。一些最基本的分頁、jquery ajax文件上傳、一個相對固定的佈局什麼的,仍是會寫的

問題

  • 其實我一直以爲個人spring和hibernate的集成方式有很大問題,不過秉持着 「能夠運行,代碼不出錯就能夠」 的想法,先這麼寫着,最近幾天我得學會使用jpa了。
  • 有就是前臺頁面的位置問題,Spring Boot 實戰 這本書上說 Boot 推薦把 視圖資源話在 src/main/resources 目錄下,而後在配置中 /WEB-INF/views/修改成/WEB-INF/classes/views/。不過我習慣放在webapp/WEB-INF/views目錄下,等到用boot的時候再說
  • 前臺的佈局,這是個大問題,很大很大的問題
相關文章
相關標籤/搜索