基于javaconfig配置的SSM框架整合demo
1、吐槽部分
现在做的这个blog项目用SSM框架,虽然环境别人都给搭建完毕了。
但是作为一个技术者,怎么能不会搭建环境呢?
Spring就提供了javaconfig的方式启动容器,在这里我们搭建一个零配置的SSM的环境;
只不过mybatis的一些高级应用暂时还需要少量的配置文件来实现(这个道听途说);
Spring boot以后基本不上不用配置文件了,xml配置你需要懂得其原理就够了,为了理解框架是如何工作的个人觉得用javaconfig注解的方式更加深刻;
关于SSM框架整合,网上大多数都是用xml和maven的方式,这里我们用最简单的eclipse做一个简短的demo;
2、我的搭建经历
搭建SSM最重要的就是Jar包,缺失jar会怎么样你知道的,关于其中的每个jar包的作用我们参考下面链接:
我的lib结构稍后我再给补充上;
为了更容易实现基于javaconfig的SSM框架,开发环境如下:
Web 应用服务器:tomcat8.5;
数据库:Oracle;
开发工具:PLSQL Developer 12 (64 bit),eclipse;
JDK:1.8;
关于Spring的jar包,没有找到Spring.jar包,我是从官网下载的
Spring
目录结构
src spittr.bean //包名 Spitter.java //类名 spittr.config //包名 DataConfig.java RootConfig.java SpitterWebInitializer.java WebConfig.java//类名 spittr.mapper SpitterMapper.java //接口 spittr.web HomeController.java SpitterController.java
首先设置Spring的启动,需要SpitterWebInitializer.java、WebConfig.java、RootConfig.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package spittr.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /* * 在Servlet3.0环境以后,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类; * Spring提供了这个接口的实现类SpringServletContainerInitializer, * 反过来这个类又去查找实现WebApplicationInitializer接口的类,并将配置任务交给他完成。 * 而Spring3.2引入了WebApplicationInitializer的实现类AbstractAnnotationConfigDispatcherServletInitializer; * 而我们的SpitterWebInitializer继承了AbstractAnnotationConfigDispatcherServletInitializer, * 因此我们部署到Servlet3.0容器中的时候,容器会自动发现他,并用它来配置Servlet上下文。 */ public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { /* * getServletMappings(),它会将一个或者多个路径映射到DispatcherServlet, * 本例中,他映射的是"/",这表示他会是应用默认的Servlet。他会处理进入该应用的所有请求。 */ @Override protected String[] getServletMappings() { return new String[] { "/" }; } /* * DispatcherServlet启动时,他会创建Spring应用的上下文,并加载配置文件或配置类中的所有生命的bean, * 我们要求DispatcherServlet加载应用上下文时,加载我们在WebConfig中的配置bean。 */ @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebConfig.class }; } /* * 但是在Spring Web中应用中,通常还会有另一个上下文,他是由ContextLoaderListener创建的, * 我们希望DispatcherServlet加载Web组件的bean,如控制器,视图解析器以及处理器映射, * ContextLoaderListener要加载应用中的其他bean,即RootConfig来实现。 */ @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { RootConfig.class }; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.config; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.ComponentScan; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.web.servlet.ViewResolver; 7 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 8 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 9 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 11 import org.springframework.web.servlet.view.InternalResourceViewResolver; 12 13 @Configuration 14 @EnableWebMvc 15 @ComponentScan("spittr.web,spittr.mapper") 16 public class WebConfig extends WebMvcConfigurerAdapter { 17 18 /* 19 * 此处配置视图解析器 20 */ 21 @Bean 22 public ViewResolver viewResolver() { 23 InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 24 resolver.setPrefix("/WEB-INF/views/"); 25 resolver.setSuffix(".jsp"); 26 return resolver; 27 } 28 29 @Override 30 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 31 configurer.enable(); 32 } 33 34 /* 35 * 静态资源处理 36 */ 37 38 @Override 39 public void addResourceHandlers(ResourceHandlerRegistry registry) { 40 super.addResourceHandlers(registry); 41 } 42 43 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.config; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 6 7 @Configuration 8 @ComponentScan 9 public class RootConfig { 10 // public static class WebPackage extends RegexPatternTypeFilter { 11 // public WebPackage() { 12 // super(Pattern.compile("spittr\\.web")); 13 // } 14 // } 15 }
到这一步我们已经把Spring以及SpringMVC启动配置类做完了,我们需要一个home.jsp和控制器HomeController.java来实现一个最简单mvc;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 <%@ page session="false" %> 3 <html> 4 <head> 5 <title>Spitter</title> 6 <link rel="stylesheet" 7 type="text/css" 8 href="<c:url value="/resources/style.css" />" > 9 </head> 10 <body> 11 <h1>Welcome to Spitter</h1> 12 13 <a href="<c:url value="/spittles" />">Spittles</a> | 14 <a href="<c:url value="/spitter/register" />">Register</a> 15 </body> 16 </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.web; 2 3 import static org.springframework.web.bind.annotation.RequestMethod.*; 4 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 9 @Controller 10 @RequestMapping("/") 11 public class HomeController { 12 13 @RequestMapping(method = GET) 14 public String home(Model model) { 15 return "home"; 16 } 17 18 }
我们启动app,浏览器输入网址http://localhost:8080/spittr/ 就会进入我们的home.jsp主页
3、整合mybatis
整合mybatis,首先我们采用数据库连接处的DataSource方式,我们需要的基本的jar包有
commons-dbcp-1.2.1.jar 用于数据库连接
commons-pool-1.6.jar 用于数据库连接
mybatis-3.4.4.jar
mybatis-spring-1.3.0.jar
spring-instrument-4.2.3.RELEASE.jar
spring-instrument-tomcat-4.2.3.RELEASE.jar
spring-jdbc-4.2.3.RELEASE.jar
spring-tx-4.2.3.RELEASE.jar
ojdbc14.jar
看到这么多Spring的包,我真希望找一个Spring.jar把他们集合在一起
以上这些应该是必须的吧
首先我们应该配置DataConfig.java这个类,因为服务器启动时候我们需要加载它,使用@Configuration声明他是个配置类;
配置连接池
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.config; 2 3 import javax.sql.DataSource; 4 5 import org.apache.commons.dbcp.BasicDataSource; 6 import org.apache.ibatis.session.SqlSessionFactory; 7 import org.mybatis.spring.SqlSessionFactoryBean; 8 import org.mybatis.spring.annotation.MapperScan; 9 import org.springframework.context.annotation.Bean; 10 import org.springframework.context.annotation.Configuration; 11 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 12 13 @Configuration 14 @MapperScan(value="spittr.mapper") 15 public class DataConfig { 16 17 @Bean 18 public DataSource dataSource() { 19 BasicDataSource dataSource = new BasicDataSource(); 20 dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); 21 dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:oracle");// 防止乱码 22 dataSource.setUsername("scott"); 23 dataSource.setPassword("tiger"); 24 dataSource.setInitialSize(5); 25 dataSource.setMaxActive(10); 26 System.out.println("------数据库连接正常-------"); 27 return dataSource; 28 } 29 30 @Bean 31 public DataSourceTransactionManager transactionManager() { 32 return new DataSourceTransactionManager(dataSource()); 33 } 34 35 @Bean 36 public SqlSessionFactory sqlSessionFactory() throws Exception { 37 SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); 38 sessionFactory.setDataSource(dataSource()); 39 return sessionFactory.getObject(); 40 } 41 42 //此处不用MapperScan也可以用下面的方式才扫面mapper 43 // @Bean 44 // public MapperScannerConfigurer scannerConfigurer() { 45 // MapperScannerConfigurer configurer = new MapperScannerConfigurer(); 46 // configurer.setBasePackage("spittr.mapper"); 47 // configurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); 48 // return configurer; 49 // } 50 51 }
然后我们创建实体类并在Oracle数据库中创建相对应的表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.bean; 2 3 import javax.validation.constraints.NotNull; 4 import javax.validation.constraints.Size; 5 6 import org.apache.commons.lang3.builder.EqualsBuilder; 7 import org.apache.commons.lang3.builder.HashCodeBuilder; 8 9 public class Spitter { 10 11 private Long id; 12 13 @NotNull 14 @Size(min = 5, max = 16) 15 private String username; 16 17 @NotNull 18 @Size(min = 5, max = 25) 19 private String password; 20 21 @NotNull 22 @Size(min = 2, max = 30) 23 private String firstName; 24 25 @NotNull 26 @Size(min = 2, max = 30) 27 private String lastName; 28 29 @NotNull 30 private String email; 31 32 public Spitter() { 33 } 34 35 public Spitter(String username, String password, String firstName, String lastName, String email) { 36 this(null, username, password, firstName, lastName, email); 37 } 38 39 public Spitter(Long id, String username, String password, String firstName, String lastName, String email) { 40 this.id = id; 41 this.username = username; 42 this.password = password; 43 this.firstName = firstName; 44 this.lastName = lastName; 45 this.email = email; 46 } 47 48 public String getUsername() { 49 return username; 50 } 51 52 public void setUsername(String username) { 53 this.username = username; 54 } 55 56 public String getPassword() { 57 return password; 58 } 59 60 public void setPassword(String password) { 61 this.password = password; 62 } 63 64 public Long getId() { 65 return id; 66 } 67 68 public void setId(Long id) { 69 this.id = id; 70 } 71 72 public String getFirstName() { 73 return firstName; 74 } 75 76 public void setFirstName(String firstName) { 77 this.firstName = firstName; 78 } 79 80 public String getLastName() { 81 return lastName; 82 } 83 84 public void setLastName(String lastName) { 85 this.lastName = lastName; 86 } 87 88 public String getEmail() { 89 return email; 90 } 91 92 public void setEmail(String email) { 93 this.email = email; 94 } 95 96 @Override 97 public boolean equals(Object that) { 98 return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email"); 99 } 100 101 @Override 102 public int hashCode() { 103 return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email"); 104 } 105 106 }
我们创建mybatis的Spitter的Mapper接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.mapper; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Delete; 6 import org.apache.ibatis.annotations.Insert; 7 import org.apache.ibatis.annotations.Param; 8 import org.apache.ibatis.annotations.Select; 9 import org.apache.ibatis.annotations.Update; 10 11 import spittr.bean.Spitter; 12 13 public interface SpitterMapper { 14 15 @Select("SELECT * FROM spitter") 16 List<Spitter> getSpitterList(); 17 18 @Select("SELECT * FROM spitter WHERE username = #{username}") 19 Spitter getSpitterByUsername(@Param("username") String username); 20 21 @Update("UPDATE spitter SET password = #{password} WHERE id = #{id}") 22 void updateSpitterEmailById(@Param("id") Long id, @Param("password") String password); 23 24 @Delete("DELETE FROM spitter WHERE id = #{id}") 25 void deleteSpitterById(@Param("id") Long id); 26 27 @Insert("insert into spitter(id,username,password,firstName,lastName,email) values(#{id},#{username},#{password},#{firstName},#{lastName},#{email})") 28 void insertSpitter(Spitter spitter); 29 30 // void save(Spitter spitter); 31 32 Spitter findByUsername(String username); 33 34 }
然后创建控制器SpitterController.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spittr.web; 2 3 import static org.springframework.web.bind.annotation.RequestMethod.*; 4 5 import javax.validation.Valid; 6 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.ui.Model; 10 import org.springframework.validation.Errors; 11 import org.springframework.web.bind.annotation.PathVariable; 12 import org.springframework.web.bind.annotation.RequestMapping; 13 14 import spittr.bean.Spitter; 15 import spittr.mapper.SpitterMapper; 16 17 @Controller 18 @RequestMapping("/spitter") 19 public class SpitterController { 20 21 private SpitterMapper spitterMapper; 22 23 @Autowired 24 public SpitterController(SpitterMapper spitterMapper) { 25 this.spitterMapper = spitterMapper; 26 } 27 28 @RequestMapping(value="/register", method=GET) 29 public String showRegistrationForm() { 30 return "registerForm"; 31 } 32 33 @RequestMapping(value="/register", method=POST) 34 public String processRegistration( 35 @Valid Spitter spitter, 36 Errors errors) { 37 if (errors.hasErrors()) { 38 System.out.println("------registerForm-----"); 39 return "registerForm"; 40 } 41 System.out.println("--------insert before-------"); 42 System.out.println(spitterMapper); 43 System.out.println(spitter.getEmail()); 44 spitterMapper.insertSpitter(spitter); 45 System.out.println("--------insert after-------"); 46 return "redirect:/spitter/" + spitter.getUsername(); 47 } 48 49 @RequestMapping(value="/{username}", method=GET) 50 public String showSpitterProfile(@PathVariable String username, Model model) { 51 Spitter spitter = spitterMapper.getSpitterByUsername(username); 52 model.addAttribute(spitter); 53 return "profile"; 54 } 55 56 }
home.jsp注册的url为"/spitter/register"根据控制器我们进入注册页面registerForm.jsp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 <%@ page session="false" %> 3 <html> 4 <head> 5 <title>Spitter</title> 6 <link rel="stylesheet" type="text/css" 7 href="<c:url value="/resources/style.css" />" > 8 </head> 9 <body> 10 <h1>Register</h1> 11 12 <form method="POST"> 13 id: <input type="text" name="id" /><br/> 14 First Name: <input type="text" name="firstName" /><br/> 15 Last Name: <input type="text" name="lastName" /><br/> 16 Email: <input type="email" name="email" /><br/> 17 Username: <input type="text" name="username" /><br/> 18 Password: <input type="password" name="password" /><br/> 19 <input type="submit" value="Register" /> 20 </form> 21 </body> 22 </html>
点击提交按钮后我们根据控制器,进入到profile.jsp页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Spitter</title> <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />" > </head> <body> <h1>Register</h1> <form method="POST"> id: <input type="text" name="id" /><br/> First Name: <input type="text" name="firstName" /><br/> Last Name: <input type="text" name="lastName" /><br/> Email: <input type="email" name="email" /><br/> Username: <input type="text" name="username" /><br/> Password: <input type="password" name="password" /><br/> <input type="submit" value="Register" /> </form> </body> </html>
到此我们就完成了插入数据和注册功能。
如有疑问可以发送simple321@vip.qq.com;