SSM整合小案例
案例介绍:
Hello!大家好,我是在校的卑微技术狗,在这里分享一个SSM小Demo,此案例将实现的功能有:
1.查询数据库将数据展示到浏览器,
2.前端表单填写数据增加到数据库中,
功能简单,却是大楼的基础,以后的项目都可以在此基础上衍生。如有错误不妥之处,请大佬们指出不足,一起学习分享交流。话不多述直接上代码。
这是案例的项目文件总览,
下面我们按照项目文件开始创建,关于jar包,就直接导入SSM所有相关jar包就可以了
1.首先根据数据库内容,创建一个Student实体类,关于数据库创建我不在简述,就一个表,两个字段
package com.wangningbo.bean;
public class Student {
private Integer id;
private String name;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2.根据需求创建service接口IStudentService
package com.wangningbo.service;
import java.util.List;
import com.wangningbo.bean.Student;
public interface IStudentService {
List<Student> queryAllStudent();
void addStudent(Student student);
}
3.创建service接口的实现类StudentServiceImpl
package com.wangningbo.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wangningbo.bean.Student;
import com.wangningbo.dao.IStudentDao;
@Service("studentService")//用注解的方式,创建bean,id="studentService"
@Transactional//事务管理,一旦service方法出现异常,就会回滚到执行方法之前,具体配置见spring配置文件
public class StudentServiceImpl implements IStudentService {
@Resource//注入dao
private IStudentDao dao;
public List<Student> queryAllStudent() {
return dao.selectAllStudent();
}
public void addStudent(Student student) {
dao.insertStudent(student);
}
}
4.创建IStudengDao接口,实现对数据库的操作,因为没有特殊的service,所以dao接口和service接口差不多
package com.wangningbo.dao;
import java.util.List;
import com.wangningbo.bean.Student;
public interface IStudentDao {
List<Student> selectAllStudent();
void insertStudent(Student student);
}
5.定义mapper映射文件,实现sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wangningbo.dao.IStudentDao">
<!-- SQL语句 -->
<insert id="insertStudent" parameterType="com.wangningbo.bean.Student">
insert into student(name,age) values(#{name},#{age})
</insert>
<select id="selectAllStudent" resultType="com.wangningbo.bean.Student">
select * from student
</select>
</mapper>
6.编写jdbc.properties文件,用于存储数据库信息,log4j.properties文件就是日志输出格式的配置,也可以不用
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.user=root
jdbc.password=******
7.编写spring核心配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注册properties配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 使用properties配置文件 -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 创建SqlSessionFactory -->
<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 关联连接池 -->
<property name="dataSource" ref="myDataSource"/>
<!-- 加载Sql配置文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 直接配置mapper接口自动扫描,不一个个配置了 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wangningbo.dao"/>
</bean>
<!-- 开启spring事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myDataSource"/>
</bean>
<!-- 开启spring事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 开启spring的IOC注解扫描 -->
<context:component-scan base-package="com.wangningbo"/>
</beans>
8.创建spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:contenxt="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描Controller所在的包 -->
<contenxt:component-scan base-package="com.wangningbo.controller"/>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器:简化在Controller类编写的视图路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
9.创建myController
package com.wangningbo.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wangningbo.bean.Student;
import com.wangningbo.service.IStudentService;
@Controller
@RequestMapping("/student")
public class myController {
@Resource
private IStudentService service;
@RequestMapping("/list")
@ResponseBody//将数据转换成json
public List<Student> list(){
List<Student> students = service.queryAllStudent();
return students;
}
@RequestMapping("/input")
public String input(){
return "input";
}
@RequestMapping("/insert")
public String insert(Student student){
System.out.println(student);
service.addStudent(student);
return "index";
}
}
10.编写input.jsp和index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>input</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath }/student/insert.action" method="post">
学生姓名:<input type="text" name="name" />
学生年龄:<input type="text" name="age" />
<input type="submit" value="保存"/>
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>index</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>保存成功 </h1>
</body>
</html>
11.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- 配置SpringMVC编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 开启spring-mvc -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 配置spring-mvc配置文件的路径 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 开启spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<!-- 配置spring配置文件的路径 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
好了基础代码已经全部书写完毕,最后就是部署到tomcat上面,进行测试
1.浏览器输入http://localhost/07-myBatis-spring-springmvc/student/list.action,因为我把tomcat端口号设置成80,所以不写也行。首先测试查询功能,下面已经返回了我事先插入的测试数据,当然都是一些美女的首字母缩写,曾经暗恋过的
2.浏览器输入http://localhost/07-myBatis-spring-springmvc/student/input.action,可以填写要插入数据库的信息
跳转到这个页面就是插入成功,不信你可以用第一种方式测试,这里我不再演示