搭建SSM环境_注解版_基于maven的web项目详解

广告位

  一.基本信息: 数据库 CREATE DATABASE webdemo001; USE webd…

 

一.基本信息:

数据库

CREATE DATABASE webdemo001; USE webdemo001; CREATE TABLE t_student(   sid INT PRIMARY KEY AUTO_INCREMENT,   student_name VARCHAR(50),   age INT ); INSERT INTO t_student(student_name,age) VALUES('jack',18); INSERT INTO t_student(student_name,age) VALUES('rose',21);

JavaBean

@Table(name = "t_student") public class Student {     @Id     private Integer sid;      @Column(name = "student_name")     private String studentName;      private Integer age;      @Override     public String toString() {         return "Student{" +                 "sid=" + sid +                 ", studentName='" + studentName + ''' +                 ", age=" + age +                 '}';     }      public Integer getSid() {         return sid;     }      public void setSid(Integer sid) {         this.sid = sid;     }      public String getStudentName() {         return studentName;     }      public void setStudentName(String studentName) {         this.studentName = studentName;     }      public Integer getAge() {         return age;     }      public void setAge(Integer age) {         this.age = age;     }      public Student() {     }      public Student(Integer sid, String studentName, Integer age) {         this.sid = sid;         this.studentName = studentName;         this.age = age;     }

二.maven web项目:注解版

搭建SSM环境_注解版_基于maven的web项目详解

1. pom.xml坐标

<?xml version="1.0" encoding="UTF-8"?>  <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">     <parent>         <artifactId>ssm_all</artifactId>         <groupId>com.czxy</groupId>         <version>1.0-SNAPSHOT</version>     </parent>     <modelVersion>4.0.0</modelVersion>      <artifactId>web_annotation</artifactId>     <packaging>war</packaging>       <!-- 统一版本控制 -->     <properties>         <mysql.version>5.1.32</mysql.version>         <druid.version>1.0.31</druid.version>         <mybatis.version>3.4.6</mybatis.version>         <mapper.version>3.5.3</mapper.version>         <mybatis.spring.version>1.3.2</mybatis.spring.version>         <spring.version>5.1.6.RELEASE</spring.version>         <pagehelper.version>5.1.2</pagehelper.version>         <jsp.version>2.1</jsp.version>         <servlet.version>3.1.0</servlet.version>         <jstl.version>1.2</jstl.version>         <jackson.version>2.9.8</jackson.version>     </properties>      <dependencies>         <!-- mysql驱动 -->         <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <version>${mysql.version}</version>         </dependency>         <!-- druid连接池 -->         <dependency>             <groupId>com.alibaba</groupId>             <artifactId>druid</artifactId>             <version>${druid.version}</version>         </dependency>         <!-- mybatis和通用mapper,整合jar -->         <dependency>             <groupId>org.mybatis</groupId>             <artifactId>mybatis</artifactId>             <version>${mybatis.version}</version>         </dependency>         <dependency>             <groupId>tk.mybatis</groupId>             <artifactId>mapper</artifactId>             <version>${mapper.version}</version>         </dependency>         <dependency>             <groupId>org.mybatis</groupId>             <artifactId>mybatis-spring</artifactId>             <version>${mybatis.spring.version}</version>         </dependency>         <!-- spring -->         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-context</artifactId>             <version>${spring.version}</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-aspects</artifactId>             <version>${spring.version}</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-jdbc</artifactId>             <version>${spring.version}</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-test</artifactId>             <version>${spring.version}</version>         </dependency>         <!-- 分页助手 -->         <dependency>             <groupId>com.github.pagehelper</groupId>             <artifactId>pagehelper</artifactId>             <version>${pagehelper.version}</version>         </dependency>         <!-- spring mvc -->         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-webmvc</artifactId>             <version>${spring.version}</version>         </dependency>         <!-- jsp/servlet/jstl                          -->         <dependency>             <groupId>javax.servlet.jsp</groupId>             <artifactId>jsp-api</artifactId>             <version>${jsp.version}</version>             <scope>provided</scope>         </dependency>         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>${servlet.version}</version>             <scope>provided</scope>         </dependency>         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>jstl</artifactId>             <version>${jstl.version}</version>         </dependency>         <!-- jackson spring mvc json转换工具 -->         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-databind</artifactId>             <version>${jackson.version}</version>         </dependency>     </dependencies>      <build>         <plugins>             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-compiler-plugin</artifactId>                 <version>3.5.1</version>                 <configuration>                     <source>1.8</source>                     <target>1.8</target>                 </configuration>             </plugin>             <plugin>                 <groupId>org.apache.tomcat.maven</groupId>                 <artifactId>tomcat7-maven-plugin</artifactId>                 <version>2.2</version>                 <configuration>                     <port>8080</port>                     <path>/</path>                 </configuration>             </plugin>         </plugins>     </build> </project> 

2.​​​​​​​配置类:MyBatis

搭建SSM环境_注解版_基于maven的web项目详解

MyBatisConfiguration .class

package com.czxy.webdemo.config;  import com.github.pagehelper.PageInterceptor; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import tk.mybatis.spring.mapper.MapperScannerConfigurer;  import javax.sql.DataSource; import java.util.Properties;  public class MyBatisConfiguration { 	/** 	 * 配置session工厂 	 * @param dataSource 	 * @return 	 * @throws Exception 	 */ 	@Bean 	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{ 		//1 创建 factoryBean 		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); 		//2 设置数据 		// 2.1 数据源  		factoryBean.setDataSource(dataSource); 		 		// 2.2 驼峰命名 		Configuration configuration = new Configuration(); 		configuration.setMapUnderscoreToCamelCase(true); 		factoryBean.setConfiguration(configuration); 		 		// 2.3 分页插件 		Properties props = new Properties(); 		// 设置方言 		props.setProperty("helperDialect", "mysql"); 		// 分页的同时进行count查询 		props.setProperty("rowBoundsWithCount", "true"); 		// 分页合理化参数,pageNum<=0 时会查询第一页,pageNum>pages (超过总数时),会查询最后一页 		props.setProperty("reasonable", "true");  		PageInterceptor pageInterceptor = new PageInterceptor(); 		pageInterceptor.setProperties(props);  		factoryBean.setPlugins(new Interceptor[] {pageInterceptor}); 		 		//3 通过factorybean获得对应 		return factoryBean.getObject(); 	} 	/** 	 * 映射扫描器 	 * @return 	 */ 	@Bean 	public MapperScannerConfigurer mapperScannerConfigurer(){ 		//1 创建 		MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer(); 		//2设置包 		mapperScanner.setBasePackage("com.czxy.webdemo.mapper"); 		 		return mapperScanner; 	}  } 

​​​​​​​3.配置类:Spring

搭建SSM环境_注解版_基于maven的web项目详解

db.properties 文件中配置数据相关信息

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/webdemo001 jdbc.username=root jdbc.password=1234 

SpringConfiguration 配置spring 数据库/事务相关信息

package com.czxy.webdemo.config;  import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement;  import javax.sql.DataSource;  @ComponentScan(basePackages="com.czxy.webdemo.service") @PropertySource("classpath:db.properties") @EnableTransactionManagement public class SpringConfiguration { 	/** 	 * 获得properties文件中内容,并注入对应变量 	 */ 	@Value("${jdbc.driver}") 	private String driver; 	 	@Value("${jdbc.url}") 	private String url; 	 	@Value("${jdbc.username}") 	private String username; 	 	@Value("${jdbc.password}") 	private String password; 	/** 	 * 配置数据源 	 * @return 	 */ 	@Bean 	public DataSource dataSource(){ 		DruidDataSource druidDataSource = new DruidDataSource();  		druidDataSource.setDriverClassName(driver); 		druidDataSource.setUrl(url); 		druidDataSource.setUsername(username); 		druidDataSource.setPassword(password); 		return druidDataSource; 	} 	/** 	 * 修复spring4.2bug 	 * @return 	@Bean 	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){ 		return new PropertySourcesPlaceholderConfigurer(); 	} 	 */  	/** 	 * 事务管理器 	 * @param dataSource 	 * @return 	 */ 	@Bean 	public DataSourceTransactionManager txManager(DataSource dataSource){ 		return new DataSourceTransactionManager(dataSource); 	}  } 

4.​​​​​​​配置类:Spring MVC

搭建SSM环境_注解版_基于maven的web项目详解

package com.czxy.webdemo.config;  import com.github.pagehelper.PageInterceptor; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import tk.mybatis.spring.mapper.MapperScannerConfigurer;  import javax.sql.DataSource; import java.util.Properties;  public class MyBatisConfiguration { 	/** 	 * 配置session工厂 	 * @param dataSource 	 * @return 	 * @throws Exception 	 */ 	@Bean 	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{ 		//1 创建 factoryBean 		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); 		//2 设置数据 		// 2.1 数据源  		factoryBean.setDataSource(dataSource); 		 		// 2.2 驼峰命名 		Configuration configuration = new Configuration(); 		configuration.setMapUnderscoreToCamelCase(true); 		factoryBean.setConfiguration(configuration); 		 		// 2.3 分页插件 		Properties props = new Properties(); 		// 设置方言 		props.setProperty("helperDialect", "mysql"); 		// 分页的同时进行count查询 		props.setProperty("rowBoundsWithCount", "true"); 		// 分页合理化参数,pageNum<=0 时会查询第一页,pageNum>pages (超过总数时),会查询最后一页 		props.setProperty("reasonable", "true");  		PageInterceptor pageInterceptor = new PageInterceptor(); 		pageInterceptor.setProperties(props);  		factoryBean.setPlugins(new Interceptor[] {pageInterceptor}); 		 		//3 通过factorybean获得对应 		return factoryBean.getObject(); 	} 	/** 	 * 映射扫描器 	 * @return 	 */ 	@Bean 	public MapperScannerConfigurer mapperScannerConfigurer(){ 		//1 创建 		MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer(); 		//2设置包 		mapperScanner.setBasePackage("com.czxy.webdemo.mapper"); 		 		return mapperScanner; 	}  } 

5.​​​​​​​配置类:初始化加载类

搭建SSM环境_注解版_基于maven的web项目详解

package com.czxy.webdemo.config;  import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.DispatcherServlet;  import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration;  public class WebInitializer implements WebApplicationInitializer {  	@Override 	public void onStartup(ServletContext servletContext) throws ServletException { 		//1 配置spring工厂 		AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext(); 		// 注册所有的配置类 		application.register(MyBatisConfiguration.class); 		application.register(SpringConfiguration.class); 		application.register(MvcConfiguration.class); 		 		//2 post中文乱码 		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8")); 		encodingFilter.addMappingForUrlPatterns(null, true, "/*"); 		 		//3 核心控制器 		ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application)); 		//mvcServlet.addMapping("*.action"); 		mvcServlet.addMapping("/"); 		mvcServlet.setLoadOnStartup(2);	//tomcat启动时,执行servlet的初始化方法 		 	}  } 

6.功能:查询所有

搭建SSM环境_注解版_基于maven的web项目详解

步骤一:编写Mapper

@org.apache.ibatis.annotations.Mapper public interface StudentMapper extends Mapper<Student> { }

步骤二:编写service

搭建SSM环境_注解版_基于maven的web项目详解

接口

public interface StudentService {     /**      * 查询所有      * @return      */     List<Student> findAll(); } 

实现类

@Service @Transactional public class StudentServiceImpl implements StudentService {     @Resource     private StudentMapper studentMapper;          @Override     public List<Student> findAll() {         return studentMapper.selectAll();     } }

步骤三:编写controller

controller确定视图的名称

@Controller @RequestMapping("/student") public class StudentController {     @Resource     private StudentService studentService;      @GetMapping     public String findAll(Model model) {         //查询所有         List<Student> slist = studentService.findAll();         //存放到作用域         model.addAttribute("list", slist);         return "student_list";     } }

编写jsp,显示查询结果

<%@ page language="java" contentType="text/html; charset=UTF-8"          pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body>  <table border="1">      <tr>          <td>编号</td>          <td>姓名</td>          <td>年龄</td>          <td>操作</td>      </tr>      <c:forEach items="${list}" var="student" varStatus="vs">          <tr>              <td>${vs.count}</td>              <td>${student.studentName}</td>              <td>${student.age}</td>          <td>              修改              删除          </td>          </tr>      </c:forEach>  </table> </body> </html> 

步骤四:首页

搭建SSM环境_注解版_基于maven的web项目详解

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>web巩固案例</title> </head> <body>     <a href="/student">查询所有</a> </body> </html>

步骤五:启动

搭建SSM环境_注解版_基于maven的web项目详解

浏览器:

搭建SSM环境_注解版_基于maven的web项目详解

看完恭喜你,又知道了一点点!!!

你知道的越多,不知道的越多! 

~感谢志同道合的你阅读,  你的支持是我学习的最大动力 ! 加油 ,陌生人一起努力,共勉!!

情葬死海

关于作者: 情葬死海

为您推荐