免配置文件SSM环境搭建

原创
2016/08/02 13:50
阅读数 483

注:项目运行的环境要是选择安装的jdk,如C:\Program Files\Java\jdk1.8.0_91,如果选择了jre,会提示:

org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required

项目整体结构如下:

1.pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>hui</groupId>
	<artifactId>SSM</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>rest.jerseySpring Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-core</artifactId>
			<version>1.3</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.13</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.1</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.4</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.1-GA</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>


		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.jaxrs</groupId>
			<artifactId>jackson-jaxrs-json-provider</artifactId>
			<version>2.5.4</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.4</version>
		</dependency>


		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>9.3.7.v20160115</version>
		</dependency>

		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-servlet</artifactId>
			<version>9.3.7.v20160115</version>
		</dependency>

		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-webapp</artifactId>
			<version>9.3.7.v20160115</version>
		</dependency>
		
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-jsp</artifactId>
			<version>9.2.15.v20160210</version>
		</dependency>
	</dependencies>
	<build>
		<resources>
			<resource>
				<targetPath>webapp</targetPath>
				<directory>src/main/webapp</directory>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>2.4 </version>
					<configuration>
						<warSourceDirectory> src/main/webapp</warSourceDirectory>
						<warName>SSM</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>

		<finalName>SSM</finalName>
	</build>

</project>

2.src/main/resources/log4j.properties:

log4j.rootLogger=info,stdout
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] -%m%n  
 
 
log4j.logger.com.ibatis=debug
#print package soc.dao  sql 
#level from high to low :OFF FATAL ERROR WARN INFO DEBUG TRACE ALL
log4j.logger.soc.dao=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout

3.src/main/resources/conf.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8

jdbc.username=root

jdbc.password=java

4.com.config.SpringJavaConfiguration .java:

package com.config;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.io.Resources;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
@ComponentScan(basePackages = { "com" })
public class SpringJavaConfiguration {
	@Bean(autowire = Autowire.BY_TYPE)
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		Properties prop = null;
		try {
			prop = Resources.getResourceAsProperties("conf.properties");
			String driverClass = prop.getProperty("jdbc.driverClassName");
			String jdbcUrl = prop.getProperty("jdbc.url");
			String uname = prop.getProperty("jdbc.username");
			String password = prop.getProperty("jdbc.password");

			dataSource.setDriverClassName(driverClass);
			dataSource.setUrl(jdbcUrl);
			dataSource.setUsername(uname);
			dataSource.setPassword(password);
			dataSource.setRemoveAbandonedTimeout(60);
			dataSource.setRemoveAbandoned(true);
			dataSource.setLogAbandoned(false);
			dataSource.setMinIdle(10);
			dataSource.setMinEvictableIdleTimeMillis(30000);
			dataSource.setMaxWait(10);
			dataSource.setInitialSize(2);
			dataSource.setMaxActive(10);
			dataSource.setTimeBetweenEvictionRunsMillis(30000);
			dataSource.setValidationQuery("SELECT 1");
			dataSource.setTestOnReturn(false);
			dataSource.setTestOnBorrow(true);
			dataSource.setTestWhileIdle(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataSource;

	}

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean getSqlSesssionFactoryBean() {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource());
		/*ClassPathResource re = new ClassPathResource("myBatisConfig.xml");
		bean.setConfigLocation(re);*/
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource[] resources;
		try {
			resources = resolver.getResources("classpath:com/mapper/*Mapper.xml");
			bean.setMapperLocations(resources);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bean;
	}

	@Bean(name = "mapper", autowire = Autowire.BY_NAME)
	public MapperScannerConfigurer getMapperScannerConfigurer() {
		MapperScannerConfigurer conf = new MapperScannerConfigurer();
		conf.setBasePackage("com.dao");
		conf.setSqlSessionFactoryBeanName("sqlSessionFactory");
		return conf;
	}
}

5.com.config.WebMvcConfig .java:

/**
 * Project Name:SSM
 * Copyright (c) 2016, huibaozh@gmail.com All Rights Reserved.
*/

package com.config;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * Date: 2016年7月29日 下午7:46:06
 * 
 * @author xuyangbao3
 * @since JDK 1.8
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		final ObjectMapper objectMapper = this.buildObjectMapper();
		objectMapper.registerModule(this.getModule());
		converter.setObjectMapper(objectMapper);
		converters.add(converter);
		super.configureMessageConverters(converters);
	}

	public ObjectMapper buildObjectMapper() {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		objectMapper.setPropertyNamingStrategy(
				PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return objectMapper;
	}

	private SimpleModule getModule() {
		// Register custom serializers
		SimpleModule module = new SimpleModule("DefaultModule");

		return module;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/css/**").addResourceLocations("/css/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("/img/**").addResourceLocations("/img/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("/js/**").addResourceLocations("/js/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("/pages/**").addResourceLocations("/pages/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("*.html").addResourceLocations("/")
				.setCachePeriod(31556926);
		//不然html页面无法访问

	}

	//	@Bean
	//	public InternalResourceViewResolver getInternalResourceViewResolver() {
	//		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
	//		resolver.setPrefix("/pages/");
	//		resolver.setSuffix(".jsp");
	//		resolver.setOrder(1);
	//		return resolver;
	//	}

	//	@Bean
	//	public ViewResolver getViewResolver() {
	//		FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
	//		resolver.setCache(true);
	//		resolver.setPrefix("");
	//		resolver.setSuffix(".ftl");
	//		resolver.setOrder(1);
	//		return resolver;
	//	}

	//	@Bean
	//    public FreeMarkerConfigurer getFreemarkerConfig() {
	//        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
	//        result.setTemplateLoaderPath("/pages/");
	//        return result;
	//    }   
}

6.com.config.ComMain.java:

package com.config;

import java.io.IOException;

import org.apache.jasper.servlet.JspServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ComMain {

	private static final Logger LOGGER = LoggerFactory.getLogger(ComMain.class);

	private static final int PORT = 8888;

	private static final String CONTEXT_PATH = "/";
	private static final String CONFIG_LOCATION_PACKAGE = "com.config";
	//	private static final String MAPPING_URL = "/rest/*";
	private static final String MAPPING_URL = "/";
	/**
	 * 如果是/,则所有路径都会被mvc-dispatcher拦截,默认静态页面是不能访问的,
	 * 这时要在WebMvcConfig里将这些静态页面设为不被spring拦截器处理
	 */
	private static final String WEBAPP_DIRECTORY = "src/main/webapp";

	public static void main(String[] args) throws Exception {
		new ComMain().startJetty(PORT);
	}

	private void startJetty(int port) throws Exception {
		LOGGER.debug("Starting server at port {}", port);
		Server server = new Server(port);

		//		server.setHandler(getWebAppContext());
		server.setHandler(getServletContextHandler());
		addRuntimeShutdownHook(server);
		server.start();
		LOGGER.info("Server started at port {}", port);
		server.join();
	}

	private static ServletContextHandler getServletContextHandler() throws IOException {
		ServletContextHandler contextHandler = new ServletContextHandler(
				ServletContextHandler.SESSIONS); // SESSIONS requerido para JSP 
		contextHandler.setErrorHandler(null);

		contextHandler.setResourceBase(WEBAPP_DIRECTORY);
		contextHandler.setContextPath(CONTEXT_PATH);

		// JSP
		contextHandler.setClassLoader(Thread.currentThread().getContextClassLoader()); // Necesario para cargar JspServlet
		contextHandler.addServlet(JspServlet.class, "*.jsp");
		//不加jspServlet,.jsp文件访问时会报404

		// Spring
		WebApplicationContext webAppContext = getWebApplicationContext();
		DispatcherServlet dispatcherServlet = new DispatcherServlet(webAppContext);
		ServletHolder springServletHolder = new ServletHolder("mvc-dispatcher",
				dispatcherServlet);
		contextHandler.addServlet(springServletHolder, MAPPING_URL);
		contextHandler.addEventListener(new ContextLoaderListener(webAppContext));

		return contextHandler;
	}

	private static WebApplicationContext getWebApplicationContext() {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.setConfigLocation(CONFIG_LOCATION_PACKAGE);
		return context;
	}

	private static void addRuntimeShutdownHook(final Server server) {
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				if (server.isStarted()) {
					server.setStopAtShutdown(true);
					try {
						server.stop();
					} catch (Exception e) {
						System.out.println(
								"Error while stopping jetty server: " + e.getMessage());
						LOGGER.error(
								"Error while stopping jetty server: " + e.getMessage(),
								e);
					}
				}
			}
		}));
	}

}

7.com.controller.PersonController.java:

package com.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.entity.Person;
import com.service.PersonService;

@RestController
@RequestMapping("person")
public class PersonController {

	// @Autowired
	@Resource // 必须跟类上的声明@Component等结合使用,否则NullPointerException
	// @Inject
	private PersonService userService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

	@RequestMapping("{id}")
	public Person getUserById(@PathVariable("id") Integer id) {
		System.out.println(userService);
		return userService.getUserById(id);
	}

	@RequestMapping("all")
	public List<Person> getAllUsers() {
		return userService.query();
	}

	@RequestMapping("count")
	public Integer getCount() {
		return userService.query().size();
	}

	@RequestMapping("{id}/section")
	public Map querySection(@PathVariable("id") Integer id) {
		return userService.querySection(id);
	}

	@RequestMapping("{id}/getBirthday")
	public String getBirthday(@PathVariable("id") Integer id) {
		return userService.getBirthday(id).toGMTString();
	}

	@RequestMapping("{id}/sectionName")
	public String querySectionName(@PathVariable("id") Integer id) {
		return (String) userService.querySection(id).get("name");
	}

	@RequestMapping("birthday")
	//http://localhost:8888/person/birthday?date=2015-10-15。如不加initBinder,则date=2015/10/12也是可以的
	public List<Person> queryByBirthday(@RequestParam("date") Date date) {
		return userService.queryByBirthday(date);
	}

}

8.com.service.PersonService.java:

package com.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.PersonDao;
import com.entity.Person;

@Service("userService")
public class PersonService {
	@Autowired
	private PersonDao userDao;

	public PersonDao getMapper() {
		return userDao;
	}

	public Person getUserById(Integer userId) {
		return userDao.getUserById(userId);
	}

	public List<Person> query() {
		return (List<Person>) userDao.query();
	}

	public Map querySection(Integer id) {
		return userDao.querySection(id);
	}

	public List<Person> queryByBirthday(Date date) {
		return userDao.queryByBirthday(date);
	}

	public Date getBirthday(int id) {
		return userDao.getBirthday(id);
	}
}

 

9.com.dao.PersonDao.java:

package com.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.entity.Person;

public interface PersonDao {
	@Select("select * from person where id=#{id}")
	public Person getUserById(@Param("id") Integer id);

	public List<Person> query();

	public Map querySection(Integer id);

	public List<Person> queryByBirthday(Date date);

	public Date getBirthday(int id);
}

 

10.com.mapper.PersonMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.PersonDao">
	<cache readOnly="true" eviction="FIFO" flushInterval="60000" />
	<resultMap id="personMap" type="com.entity.Person">
		<result column="id" property="id" />
		<result column="name" property="name" />
		<result column="salary" property="salary" />
		<result column="birthday" property="birthday" />
	</resultMap>
	<sql id="Base_Column_List">
		id,name,salary,birthday
	</sql>
	<select id="query" resultMap="personMap" useCache="true">
		select
		<include refid="Base_Column_List" />
		from person
	</select>
	<select id="querySection" resultType="map" parameterType="integer"
		useCache="true">
		select
		name,salary
		from person where
		<if test="_parameter !=null"></if>
		id=#{_parameter}
	</select>
	<select id="queryByBirthday" resultMap="personMap"
		parameterType="java.util.Date" useCache="true">
		select
		* from person where
		<if test="_parameter !=null"></if>
		birthday> #{_parameter}
	</select>

	
	<select id="getBirthday" resultType="java.util.Date"
		parameterType="int" useCache="true">
		select
		birthday from person where
		<if test="_parameter !=null"></if>
		id= #{_parameter}
	</select>
</mapper>   

11.src/main/webapp/index.html:

<html>
<head>
</head>
<body>
	<h1>hello jsp</h1>
</body>
</html>

12.src/main/webapp/index.jsp:

<html>
<head>
</head>
<body>
	<h1>hello liuhui</h1>
</body>
</html>

13.src/main/webapp/pages/index.jsp:

<html>
<head>
</head>
<body>
	<h1>hello pages jsp</h1>
</body>
</html>

至此,环境搭建完成。

启动ComMain里的main方法,浏览器端访问:

http://localhost:8888/person/all

http://localhost:8888/index.jsp

http://localhost:8888/pages/index.jsp

http://localhost:8888/index.html

均可成功显示指定的信息。

展开阅读全文
打赏
0
2 收藏
分享
加载中
更多评论
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部