2019独角兽企业重金招聘Python工程师标准>>>
注:项目运行的环境要是选择安装的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:
2.src/main/resources/log4j.properties:
log4j.rootLogger=info,stdoutlog4j.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.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8jdbc.username=rootjdbc.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 {@Overridepublic void configureMessageConverters(List
}
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);// JSPcontextHandler.setClassLoader(Thread.currentThread().getContextClassLoader()); // Necesario para cargar JspServletcontextHandler.addServlet(JspServlet.class, "*.jsp");//不加jspServlet,.jsp文件访问时会报404// SpringWebApplicationContext 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() {@Overridepublic 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// @Injectprivate PersonService userService;@InitBinderpublic 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
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 {@Autowiredprivate PersonDao userDao;public PersonDao getMapper() {return userDao;}public Person getUserById(Integer userId) {return userDao.getUserById(userId);}public List
}
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
}
10.com.mapper.PersonMapper.xml:
11.src/main/webapp/index.html:
hello jsp
12.src/main/webapp/index.jsp:
hello liuhui
13.src/main/webapp/pages/index.jsp:
hello pages jsp
至此,环境搭建完成。
启动ComMain里的main方法,浏览器端访问:
http://localhost:8888/person/all
http://localhost:8888/index.jsp
http://localhost:8888/pages/index.jsp
http://localhost:8888/index.html
均可成功显示指定的信息。