创建步骤:
1.新建数据库springdb, 表User(id,username,password)
2.新建web项目
3.导入jar:
1)spring的相关jar: spring-beans.jar,spring-core.jar,spring-context.jar,spring-expression.jar
spring-aop.jar, spring-jdbc.jar,spring-tx.jar,spring-web.jar,spring-webmvc.jar
2)mybatis相关jar: mybatis-3.4.5.jar, mybatis-spring-1.3.1.jar
3)jackson工具库的三个jar
4)mysql的驱动, 数据库连接池的jar(druid-1.1.9.jar),日志的jar(commons-logging.jar, log4j.jar)
4.重点。 修改web.xml文件
1)注册spring的监听器ContextLoaderListener. 创建spring的容器对象,加载spring的配置文件(Service,Dao对象就能创建出来了)
2)注册springmvc的中央调度器,创建springmvc的容器对象,加载springmvc配置文件,创建Controller对象。
3)注册字符集过滤器,解决post请求乱码的问题。
<?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">
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 监听器默认xml扫描路径是WEB-INF下的applicationContext.xml 可以自定义路径 param-name是监听器父类的属性 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<!-- 注册监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 注册中央调度器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- springmvc 配置文件 自定义路径 -->
<param-value>classpath:conf/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- <servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> -->
<!-- url-pattern为/时 需要在mvc配置文件中配置静态资源的处理 否则js,图片等无法加载-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 注册字符集过滤器 -->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5.定义包的结构, 实体类的包名, Dao的包名, Service的包名,Controller的包名,整体架构如下
6.编写配置文件
1)springmvc的配置文件:dispatcherServlet.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: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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- springmvc配置文件:管理定义视图层的对象(处理器对象和视图解析器) -->
<!-- 声明组件扫描器 controller注解扫描 -->
<context:component-scan base-package="com/zm/ssm/controller" />
<!-- 声明视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 声明注解驱动 -->
<mvc:annotation-driven/>
<!-- 加入静态资源的处理 -->
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!-- 将spring和springmvc的配置文件合并只需要把spring的配置文件直接粘贴过来即可 -->
</beans>
2)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"
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">
<!-- 声明注解扫描器 扫面service注解所在的包 -->
<context:component-scan base-package="com/zm/ssm/service" />
<!-- 加载属性配置文件 -->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!-- 声明数据源dataSource 使用druid数据库连接池 -->
<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 创建sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定数据源DataSource -->
<property name="dataSource" ref="dataSource1" />
<!-- 指定mybatis主配置文件 -->
<property name="configLocation" value="classpath:conf/mybatis.xml"></property>
</bean>
<!-- 使用MyBatis的动态代理,创建Dao接口的实现类对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定SQLSessionFactor -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!-- 指定DAO所在的包 -->
<property name="basePackage" value="com.zm.ssm.dao" />
</bean>
</beans>
3)mybatis的主配置文件:mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 别名 -->
<typeAliases>
<package name="com.zm.ssm.domain"/>
</typeAliases>
<!-- sql映射文件 -->
<mappers>
<package name="com.zm.ssm.dao"/>
</mappers>
</configuration>
4)数据库的属性配置文件:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF8
jdbc.user=root
jdbc.password=root
7.定义实体类
User.java
public class User {
private String id;
private String password;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
8.定义Dao接口和sql映射文件
UserDao.java
public interface UserDao {
int addUser(User user);
List<User> listUser();
}
UserDao.xml
<?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.zm.ssm.dao.UserDao">
<insert id="addUser">
insert into users(username,password) values(#{username},#{password})
</insert>
<select id="listUser" resultType="User">
select id,username,password from users order by id desc
</select>
</mapper>
9.定义Service接口和实现类
UserService.java
public interface UserService {
int addUser(User user);
List<User> listUser();
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
//byType装配
@Autowired
private UserDao userDao;
@Override
public int addUser(User user) {
return userDao.addUser(user);
}
@Override
public List<User> listUser() {
List<User> userList = userDao.listUser();
return userList;
}
}
10.定义Controller类
UserController.java
@Controller
@RequestMapping(value="user") //模块名
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="add.do")
public ModelAndView addUser(User user) {
ModelAndView mv = new ModelAndView();
int rows = userService.addUser(user);
if (rows > 0) {
mv.addObject("msg", "用户" + user.getUsername() + "添加成功!");
mv.setViewName("success");
}else {
mv.addObject("msg", "用户" + user.getUsername() + "添加失败!");
mv.setViewName("fail");
}
return mv;
}
@RequestMapping(value="list.do")
@ResponseBody
public List<User> listUser(){
List<User> userList = userService.listUser();
if (userList == null) {
userList = new ArrayList<>();
}
return userList;
}
}
JumpController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("jump")
public class JumpController {
//跳转到某个jsp
@RequestMapping("tojsp.do")
public String jumpToJsp(String target){
//视图的逻辑名称(文件名)
return target;
}
}
11.定义视图文件(jsp)
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- <%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%-- <base href="<%=basePath%>"> --%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面</title>
</head>
<body>
<div align="center">
<p>整合SSM</p>
<table>
<tr>
<td><a href="${pageContext.request.contextPath }/jump/tojsp.do?target=addUser">注册用户</a></td>
<td></td>
<td><a href="${pageContext.request.contextPath }/jump/tojsp.do?target=listUser">查询用户</a></td>
</tr>
</table>
</div>
<img alt="无法加载图片" src="${pageContext.request.contextPath }/images/girl.jpg">
</body>
</html>
addUser.jap
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>新增用户</title>
</head>
<body>
<div align="center">
<p>addUser.jsp</p>
<form action="${pageContext.request.contextPath }/user/add.do" method="post">
<table>
<tr>
<td>账号:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="注册用户" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
listUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>查询用户</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.1-min.js"></script>
<script type="text/javascript">
$(function(){
UserInfo()
})
function UserInfo(){
$.ajax({
url:"${pageContext.request.contextPath }/user/list.do",
type:"post",
success:function(resp){
//[]
$("#tbody").html("");
$.each(resp,function(i,n){
$("#tbody").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.username+"</td>")
.append("<td>"+n.password+"</td>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table border="1" cellspacing="0">
<thead>
<tr>
<td>id</td>
<td>账号</td>
<td>密码</td>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
success.jsp <br>
msg: ${msg }
</body>
</html>
fail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
fail.jsp <br>
msg: ${msg }
</body>
</html>
运行结果
访问http://localhost:8080/SSM
注册用户
查询用户