关于springMVC的配置,可以参考这篇文章的第一个小节:
【java】intellij idea SpringMVC 配置FreeMarker模板引擎
码云:TestSSM
咳咳,开个玩笑,如果本着学习态度的话,那就慢慢啃吧~
使用Intellij idea 搭建基本的maven空项目 new->project
填写GroupId和ArtifactId,next,选择项目的地址,next->new window open 在新的窗口打开
接下来我们构建项目基本骨架,:
(1)在java下新建com
(2)在com下新建springmvc
(3)在springmvc下新建controller、dao、mapping、pojo、service
(4)在service下新建impl
如下图:
这里解释一个mybatis的工具,叫做mybatis-generator-core-1.3.2,它能够根据数据库中的表生成dao、mapping、pojo三个类型文件(后面会在mybatis部分详细介绍)
目录解释如下:
controller:http(GET和POST等)请求的入口,调用Service,想客户端返回数据
dao:接口,有mybatis自动化工具生成的文件之一,定义了数据表映射成的对象,具有的操作
mapping:具体是sql语句,以xml格式存在,即mybatis的语法文件
pojo:实体类
service:controller调用的服务,service调用dao里面定义的数据库行为方法,来执行对应mapping里的mybatis,从而完成与数据库完整的交互。
service-impl:接口,定义了服务应该具有的函数方法(此处可以理解是提现软件的设计思想,你要是乐意,直接写service也可以)
setting.xml镜像配置:(具体可以百度一下其他文章)
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/public/url>
<mirrorOf>centralmirrorOf>
mirror>
第二步:在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.0modelVersion>
<groupId>hugogroupId>
<artifactId>exampleartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>hugo Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.version>4.1.4.RELEASEspring.version>
<mybatis.version>3.2.8mybatis.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
<jackson.version>2.5.0jackson.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.30version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.1.41version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.13version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.1.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.1.0version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.9version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>RELEASEversion>
dependency>
<dependency>
<groupId>org.jsoupgroupId>
<artifactId>jsoupartifactId>
<version>1.8.1version>
dependency>
<dependency>
<groupId>net.sourceforge.htmlunitgroupId>
<artifactId>htmlunitartifactId>
<version>2.15version>
dependency>
<dependency>
<groupId>org.seleniumhq.seleniumgroupId>
<artifactId>selenium-javaartifactId>
<version>2.33.0version>
dependency>
<dependency>
<groupId>us.codecraftgroupId>
<artifactId>webmagic-coreartifactId>
<version>0.6.1version>
dependency>
<dependency>
<groupId>us.codecraftgroupId>
<artifactId>webmagic-extensionartifactId>
<version>0.6.1version>
dependency>
dependencies>
<build>
<finalName>hugofinalName>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
版本可自行更换,有兴趣的同学可以看看具体配置。maven的更新方式可以选择enable-auto-update(大致意思是这个,当pom文件改动时,自动更新)
第一部分:与数据库相关的jdbc.properties
在resources下新建个配置文件jdbc.properties,内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/project?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
请确保你的mysql服务是开启的,且存在数据库project
第二部分:spring-mvc
在resources下新建个配置文件spring-mvc.xml,内容如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.springmvc.controller" />
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
list>
property>
bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
list>
property>
bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
bean>
beans>
请务必仔细看里面的配置内容,尤其涉及到路径的地方
第三部分:mybatis-config.xml和spring-mybatis.xml
mybatis-config.xml配置:
<configuration>
<settings>
<setting name="logImpl" value="LOG4J" />
<setting name="cacheEnabled" value="true"/>
settings>
configuration>
此配置的作用是可以让mybatis在执行的时候打印日志,mybatis还有其他很多配置选项,有需求的小伙伴再仔细查看更详细的博文。关于mybatis的配置。
spring-mybatis配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.springmvc" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="initialSize" value="${initialSize}">property>
<property name="maxActive" value="${maxActive}">property>
<property name="maxIdle" value="${maxIdle}">property>
<property name="minIdle" value="${minIdle}">property>
<property name="maxWait" value="${maxWait}">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis-config.xml">property>
<property name="mapperLocations" value="classpath:com/springmvc/mapping/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.springmvc.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
beans>
请务必仔细看里面的配置内容,尤其涉及到路径的地方很多地方出现错误,都是因为spring或mybatis自动扫描的路径错误,导致mapping无法被识别。
第四部分:log4j.xml和log4j.properties
log4j.xml
日志模块的配置:
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jakarta.apache.org/log4j/ ">
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%c]-[%t] %x - %m%n"/>
layout>
appender>
<logger name="org.apache.ibatis" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="org.mybatis.spring" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="java.sql" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="java.sql.Connection" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="java.sql.Statement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="java.sql.PreparedStatement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="org.springframework" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
logger>
<logger name="org.apache.activemq" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
logger>
<root>
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
root>
log4j:configuration>
log4j.properties
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
以上只是基本配置,如果有其他需求,自行查阅log4j的相关资料。
第一步:将配置文件添加入工程
web.xml文件
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mybatis.xmlparam-value>
context-param>
<context-param>
<param-name>log4jRefreshIntervalparam-name>
<param-value>60000param-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<servlet>
<servlet-name>mvc-dispatcherservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcherservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
接下来我们把webapp添加入项目工程
发现里面的web.xml地址路径错误,这里我们自行修改
第三步:添加artifacts
至此如下:
第四步:编写小测试
在controller中新建main.
点击运行,若无报错,则基本配置成功。
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class main {
@RequestMapping("/")
@ResponseBody
public String index(){
return "hello world";
}
}
模拟的用户登录的行为,进行测试,这里我们在数据库里新建一张表
非常简单的表结构
然后我们使用mybatis的自动生成工具mybatis-generator-core,生成pojo、mapping、dao
这里请注意包名和数据库的名称
<generatorConfiguration>
<classPathEntry location="mysql-connector-java-5.1.25-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/project" userId="root" password="123456">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
javaTypeResolver>
<javaModelGenerator targetPackage="com.springmvc.pojo" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
javaModelGenerator>
<sqlMapGenerator targetPackage="com.springmvc.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.springmvc.dao" targetProject="src">
<property name="enableSubPackages" value="true"/>
javaClientGenerator>
<table tableName="admin" domainObjectName="Admin" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>
context>
generatorConfiguration>
然后在mybatis-generator目录的lib目录上执行
Java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
接着在src目录下就能看见生成的三个文件夹
把它们拷贝到我们的工程目录里,在写一个简单的service
package com.springmvc.service;
import com.springmvc.dao.AdminMapper;
import com.springmvc.pojo.Admin;
import javax.annotation.Resource;
public class AdminService {
@Resource
private AdminMapper adminMapper;
public Admin getAdmin(int id){
Admin a=this.adminMapper.selectByPrimaryKey(id);
if(a!=null){
return a;
}
return null;
}
public int insertAdmin(Admin admin){
return this.adminMapper.insert(admin);
}
}
接下来我们在编写一下controller,在main中添加如下代码:
@RequestMapping(value = "/admin",method = RequestMethod.POST)
@ResponseBody
public int insertUser(Admin admin){
return adminService.insertAdmin(admin);
}
@RequestMapping(value = "/admin/{id}",method = RequestMethod.GET)
@ResponseBody
public Admin getUser(@PathVariable Integer id){
return adminService.getAdmin(id);
}
最后我们使用postMan来测试:
获取admin:
以上。
至此,整个项目的基本框架已经搭建完成了,我们使用空的maven项目搭建起了ssm,实现了项目的基本架构,最后如果有不明白的地方可以下载源码查看。
欢迎大家留言交流~
码云:TestSSM
【参考】
SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
使用maven创建web项目
intellij idea下使用Maven搭建SpringMVC
IDEA搭建SpringMVC并用maven配置的小例子(非常详细)
关于Java Servlet的中文乱码