springMVC+spring+mybatis 3大框架整合,各种XML配置扑面而来。而这些XML文件格式要求又很严格,整套搭下来,让人感觉写的不是java,而是XML配置文件。而网上的注解配置,并不是纯粹的0配置,还是要写一些xml配置,只是用了几个@Service,@Controller注解。
鄙人讲的配置方式是一行XML代码都不需要,什么web.xml,applicationContext.xml,springmvc.xml,统统去死吧~~~!!!
首先建立一个Maven项目,Packageing方式为war,项目结构为标准Maven WebApp结构。
pom文件如下:
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<packaging>warpackaging>
<name>ssmname>
<groupId>MyCasegroupId>
<artifactId>ssmartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<spring.version>5.0.2.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<mysql.version>5.1.6mysql.version>
<mybatis.version>3.4.5mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.7version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>compilescope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
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.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.9version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>utf-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>8080port>
<path>/SSMpath>
<uriEncoding>UTF-8uriEncoding>
configuration>
plugin>
plugins>
build>
project>
数据库表:
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) DEFAULT NULL,
`money` float DEFAULT NULL,
PRIMARY KEY (`id`)
)
一些数据库的测试数据:
id | name | money |
---|---|---|
1 | 小强 | 1000 |
2 | 小明 | 1000 |
一切准备就绪,开始动手吧。
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.util.Properties;
@MapperScan("dao")//扫描Mybatis的Mapper接口
public class DaoConfig {
/**
* 将数据源加入IOC容器
* @return 数据源
* @throws Exception
*/
@Bean("dataSource")
public DataSource getDataSource() throws Exception {
//读取配置连接数据库的配置文件信息,创建德鲁伊数据源
Properties prop=new Properties();
prop.load(this.getClass().getClassLoader().getResourceAsStream("jdbcConfig.properties"));
return DruidDataSourceFactory.createDataSource(prop);
}
/**
* 添加动态sql工厂
* @param dataSource 数据源
* @return 动态sql工厂
*/
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean;
}
}
对应dao的XML的配置片段
<context:property-placeholder location="classpath:jdbcConfig.properties" system-properties-mode="FALLBACK"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSourceFactory" factory-method="createDataSource">
<constructor-arg>
<props>
<prop key="driver">${driver}prop>
<prop key="url">${url}prop>
<prop key="username">${username}prop>
<prop key="password">${password}prop>
props>
constructor-arg>
bean>
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao"/>
<property name="sqlSessionFactoryBeanName" value="factory"/>
bean>
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration//表明此类是配置类
@ComponentScan("service.impl")// 扫描自定义的组件
@Import(DaoConfig.class)//引入dao部分的配置
@EnableTransactionManagement //开启事务管理
public class SpringConfig {
/**
* 声明式事务
* @param dataSource 数据源
* @return 事务管理对象
*/
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
对应service的XML的配置片段
<context:component-scan base-package="service.impl"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut expression="execution(* service.impl.*.*(..))" id="txPc"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
aop:config>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import java.util.Properties;
@Configuration //springmvc的配置类
@ComponentScan("controller")//扫描包
@EnableWebMvc//开启视图
public class WebConfig implements WebMvcConfigurer {
/**
* jsp视图解析器的bean
* @return 视图解析器
*/
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
/**
* 配置静态资源的处理
*
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* 注册内置简单异常处理器
* @return 异常处理器
*/
@Bean
public SimpleMappingExceptionResolver registerExcption(){
SimpleMappingExceptionResolver exceptionResolver=new SimpleMappingExceptionResolver();
exceptionResolver.setDefaultErrorView("error");
//ex是异常对象,jsp页面要是只想取到错误信息 ${requestScope.ex.message}
exceptionResolver.setExceptionAttribute("ex");
//这里还可以继续扩展对不同异常类型的处理,往Properties添加就行
Properties prop=new Properties();
prop.put("exception.TransferException","error");
exceptionResolver.setExceptionMappings(prop);
return exceptionResolver;
}
}
对应controller的XML的配置片段
<context:component-scan base-package="controller"/>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
<property name="exceptionAttribute" value="ex"/>
<property name="exceptionMappings">
<props>
<prop key="exception.TransferException">errorprop>
props>
property>
bean>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.nio.charset.StandardCharsets;
//只要继承AbstractAnnotationConfigDispatcherServletInitializer的配置类
//使得拿掉 web.xml 成为可能
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// Spring IoC容器配置
@Override
protected Class<?>[] getRootConfigClasses() {
// 可以返回Spring的Java配置文件数组
return new Class<?>[]{SpringConfig.class};
}
// DispatcherServlet的URI映射关系配置
@Override
protected Class<?>[] getServletConfigClasses() {
// 可以返回Spring的Java配置文件数组
return new Class<?>[]{WebConfig.class};
}
// DispatchServlet拦截请求匹配
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//动态注册过滤器
//使用动态注册过滤器的API,需要用servlet依赖3.0.0以上。
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
//设置初始化参数
encodingFilter.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8));
encodingFilter.setInitParameter("forceEncoding", "true");
encodingFilter.addMappingForUrlPatterns(null, false, "/*");
/*
这里记得一定要调用父类方法,不然getServletMappings() ,getServletConfigClasses(), getRootConfigClasses()将不能生效
*/
super.onStartup(servletContext);
}
}
对应web的XML的配置片段
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext.xmlparam-value>
context-param>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:MVC/springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@RequestMapping("/test1")
public String test() {
List<Account> list = accountService.findAll();
System.out.println(list);
return "success";
}
@RequestMapping("/test2")
public ModelAndView test2() {
List<Account> list = accountService.findAll();
System.out.println(list);
ModelAndView mv = new ModelAndView();
mv.addObject("list", list);
mv.setViewName("success");
return mv;
}
@RequestMapping("/test3")
public String test3(Integer sid, Integer tid, Double money) {
accountService.transfer(sid, tid, money);
return "success";
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
测试1
测试2
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
成功
成功页面
姓名
零钱
${account.name}
${account.money}
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${requestScope.ex.message}
鄙人不才,抛砖引玉。提供小小案例