热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

免配置文件SSM环境搭建

2019独角兽企业重金招聘Python工程师标准注:项目运行的环境要是选择安装的jdk,如C:\ProgramFiles\Java\jdk1.8.

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

注:项目运行的环境要是选择安装的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:

4.0.0huiSSMwar0.0.1-SNAPSHOTrest.jerseySpring Maven Webapphttp://maven.apache.orgorg.springframeworkspring-core4.2.2.RELEASEorg.springframeworkspring-web4.2.2.RELEASEorg.springframeworkspring-beans4.2.2.RELEASEorg.springframeworkspring-context4.2.2.RELEASEorg.springframeworkspring-aop4.2.2.RELEASEorg.springframeworkspring-expression4.2.2.RELEASEorg.springframeworkspring-jdbc4.2.2.RELEASEorg.springframeworkspring-tx4.2.2.RELEASEorg.springframeworkspring-webmvc4.2.2.RELEASEorg.springframeworkspring-orm4.2.2.RELEASEjunitjunit4.12org.hamcresthamcrest-core1.3commons-fileuploadcommons-fileupload1.3.1commons-iocommons-io2.4mysqlmysql-connector-java5.1.38commons-loggingcommons-logging1.2org.slf4jslf4j-log4j121.7.13org.mybatismybatis3.3.1org.mybatismybatis-spring1.2.4org.mybatis.generatormybatis-generator-core1.3.2org.javassistjavassist3.18.1-GAcommons-dbcpcommons-dbcp1.4javax.validationvalidation-api1.1.0.Finaljavax.injectjavax.inject1com.fasterxml.jackson.jaxrsjackson-jaxrs-json-provider2.5.4com.fasterxml.jackson.corejackson-core2.5.4org.eclipse.jettyjetty-server9.3.7.v20160115org.eclipse.jettyjetty-servlet9.3.7.v20160115org.eclipse.jettyjetty-webapp9.3.7.v20160115org.eclipse.jettyjetty-jsp9.2.15.v20160210webappsrc/main/webappsrc/main/resourcesorg.apache.maven.pluginsmaven-war-plugin2.4 src/main/webappSSMfalseSSM

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> 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 serializersSimpleModule module = new SimpleModule("DefaultModule");return module;}@Overridepublic 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);// 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 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 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 {@Autowiredprivate PersonDao userDao;public PersonDao getMapper() {return userDao;}public Person getUserById(Integer userId) {return userDao.getUserById(userId);}public List query() {return (List) userDao.query();}public Map querySection(Integer id) {return userDao.querySection(id);}public List 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 query();public Map querySection(Integer id);public List queryByBirthday(Date date);public Date getBirthday(int id);
}

 

10.com.mapper.PersonMapper.xml:



id,name,salary,birthday

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

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


转:https://my.oschina.net/u/2430057/blog/725608



推荐阅读
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • 本文介绍了在使用MSXML解析XML文件时出现DTD禁用问题的解决方案。通过代码示例和错误信息获取方法,解释了默认情况下DTD是禁用的,以及如何启用DTD的方法。此外,还提到了网上关于该问题的信息相对较少,因此本文提供了解决方案以供参考。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • 突破MIUI14限制,自定义胶囊图标、大图标样式,支持任意APP
    本文介绍了如何突破MIUI14的限制,实现自定义胶囊图标和大图标样式,并支持任意APP。需要一定的动手能力和主题设计师账号权限或者会主题pojie。详细步骤包括应用包名获取、素材制作和封包获取等。 ... [详细]
author-avatar
blue秋夜听雨321
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有