最近在整合ssm,由于网上的版本太多,不容易照着文章整合,我自己也是照着网上的文章整合出来,我所贴出的代码,最笨的办法 你把我的代码照着打,一定能run
关于ssm整合,引入spring4.0,springmvc,mybatis的jar包,以及mybatis和mybatis整合的jar包,所需jar包下载地址:
https://pan.baidu.com/s/1AjhCQdL04aqjkmnGXmHOJQ
密码:t7yo
第一 首先引入以上jar包
第二,配置spring.xml文件 (我这里文件名字叫applicationContext.xml)
(全部贴出来了,都是自己亲测代码~~照葫芦画瓢就ok啦)
如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--数据源-链接数据库的基本信息,这里直接写,不放到*.properties资源文件中-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- 配置数据源,加载配置,也就是dataSource -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis.config.xml" />
<!--扫描 XXXmapper.xml映射文件,配置扫描的路径-->
<property name="mapperLocations" value="classpath:UserMapper.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找之中的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!--事务管理-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解扫描-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
第三步 配置 springmvc.xml (我这里叫applicationContext-mvc.xml)
<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">
<!-- 告知Spring,我们启用注解驱动 -->
<mvc:annotation-driven/>
<!-- org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,
它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,
就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。 -->
<mvc:default-servlet-handler/>
<!-- 指定要扫描的包的位置 -->
<context:component-scan base-package="com.ssm" />
<!-- 对静态资源文件的访问,因为Spring MVC会拦截所有请求,导致jsp页面中对js和CSS的引用也被拦截,
配置后可以把对资源的请求交给项目的
默认拦截器而不是Spring MVC-->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<!-- 配置Spring MVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 有时我们需要访问JSP页面,可理解为在控制器controller的返回值加前缀和后缀,变成一个可用的URL地址 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
第四步 配置mybatis配置文件 (mybatis.config.xml)
<!--
这里有个坑,这里config配置的可不是我们之前配置mybatis的那种,没有
<mapper resource="bookimp.xml" />
不需要引入,更不需要配置连接数库的地址,spring.xml都已经为你做了
-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<!--之后用于测试 -->
<typeAlias type="com.ssm.po.User" alias="User" />
</typeAliases>
</configuration>
第五步 写mybatis的mapeer.xml
<!--namespace就是与此文件对应的Dao接口的全路径 -->
<mapper namespace="com.ssm.dao.IUserDao">
<!--如下type的User就是mybatis-config.xml中配置的user -->
<resultMap id="BaseResultMap" type="User">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<!--自己配置的查询表所有数据的sql -->
<select id="selectAllUser" resultType="User">
select * from user;
</select>
<sql id="Base_Column_List">
id, name, age
</sql>
<insert id="insert" parameterType="User">
insert into user (
name,age
)
values (
#{name},#{age}
)
</insert>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<!-- 查询修改用户信息的id -->
<select id="getupdateid" resultMap="BaseResultMap"
parameterType="User">
<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
select
<include refid="Base_Column_List"></include>
from user
<where>id=#{id}</where>
</select>
<update id="update" parameterType="User">
update user set name = #{name,jdbcType=VARCHAR},age=#{age,jdbcType=INTEGER}
where id=#{id}
</update>
</mapper>
第六步 配置web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 加载Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring容器加载所有的配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置SpringMVC核心控制器,将所有的请求(除了刚刚Spring MVC中的静态资源请求)都交给Spring MVC -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<!--用来标记是否在项目启动时就加在此Servlet,0或正数表示容器在应用启动时就加载这个Servlet,
当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--为DispatcherServlet建立映射-->
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<!-- 拦截所有请求,千万注意是(/)而不是(/*) -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 设置编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
第七步 以上ssm的配置基本上有形状了接下来呈上ssm的dao层
1. IUserDao.java层
import java.util.List;
import org.springframework.stereotype.Repository;
import com.ssm.po.User;
@Repository("userDao")
public interface IUserDao {
int deleteByPrimaryKey(Integer id);
int insert(User record);
// 查询修改用户信息的id
public List<User> getupdateid(User record);
// 修改用户信息
int update(User record);
// 自己添加的,已匹配Mapper中的Sql
List<User> selectAllUser();
}
2.接下到service层
package com.ssm.service;
import java.util.List;
import com.ssm.po.User;
public interface UserService {
public List<User> getUser();
public String insert(User record);
public String deleteByPrimaryKey(Integer id);
public List<User> getupdateid(User record);
public String update(User record);
}
3. 创建一个serviceimpl来接口UserService
package com.ssm.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ssm.dao.IUserDao;
import com.ssm.po.User;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource(name = "userDao")
private IUserDao userDao;
public List<User> getUser() {
return userDao.selectAllUser();
}
public String insert(User u) {
int i = userDao.insert(u);
String message = "";
if (i > 0) {
message = "添加成功";
} else {
message = "添加失败";
}
return message;
}
public String deleteByPrimaryKey(Integer id) {
int deleteByPrimaryKey = userDao.deleteByPrimaryKey(id);
String message = "";
if (deleteByPrimaryKey > 0) {
message = "删除成功";
} else {
message = "删除失败";
}
return message;
}
public String update(User record) {
int update = userDao.update(record);
System.out.println("update ");
String message = "";
if (update > 0) {
message = "修改成功";
} else {
message = "修改失败";
}
return message;
}
public List<User> getupdateid(User record) {
return userDao.getupdateid(record);
}
}
4.然后到了UserController.java控制层
package com.ssm.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ssm.po.User;
import com.ssm.service.UserService;
@Controller
@RequestMapping(value = "/user")
public class UserController {
// 如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。
// 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
@Resource(name = "userService")
UserService userService;
@RequestMapping(value = "/list")
public ModelAndView list() {
ModelAndView mv = new ModelAndView();
List<User> userList = userService.getUser();
mv.addObject("userList", userList);
mv.setViewName("/show");
return mv;
}
@RequestMapping(value = "/insert")
public String insert(HttpServletRequest request, User u){
System.out.println(u.toString());
String inserUser = userService.insert(u);
request.setAttribute("inserUser", inserUser);
return "redirect:/user/list";
}
@RequestMapping(value = "/inserts")
public String inserts(){
return "/insert";
}
@RequestMapping(value = "/delete/{id}")
public ModelAndView delete(@PathVariable("id") int id){
System.out.println("id:"+id);
String deleteUser=userService.deleteByPrimaryKey(id);
ModelAndView mav=new ModelAndView();
mav.addObject("deleteUser", deleteUser);
//跳到提醒页,返回service里定义的方法,提醒删除成功还是失败
mav.setViewName("/delete");
return mav;
}
/**
* 查询修改用户信息的id
*/
@RequestMapping("/uid")//为方法设置访问路径
public String updateid(HttpServletRequest request, User u){
List<User> uid = userService.getupdateid(u);
request.setAttribute("uid", uid);
return "/update";
}
/**
* 修改用户信息
*/
@RequestMapping(value="/update")//为方法设置访问路径
public String update(HttpServletRequest request, User u){
String updateUser = userService.update(u);
request.setAttribute("updateUser", updateUser);
//修改信息后留在当前页
return "forward:/user/uid";
}
}
5. show.jsp 查询数据库的全部信息,由Controller层list跳转并进行遍历
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
%>
<!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>
<script type="text/javascript" src="<%=path%>/state/js/jquery.min.js"></script>
<script type="text/javascript">
//定义个方法提醒用户确定要删除吗?方法的参数就是要删除的id名
function deleteUser(id){
if(confirm("您确认删除吗?")){
//如果确定删除就访问servlet,这里超链接传值传的是方法里的参数
window.location.href="<%=path%>/user/delete/"+id;
}
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>修改</td>
<td>删除</td>
</tr>
<c:choose>
<c:when test="${not empty userList}">
<c:forEach items="${userList}" var="user" varStatus="vs">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td><a href="<%=path %>/user/uid?id=${user.id}">修改</a></td>
<td><a href="javascript:void(0)"
onclick="deleteUser(${user.id})">删除</a></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="2">无数据!</td>
</tr>
</c:otherwise>
</c:choose>
</table>
<a href="/ssm/user/inserts">insert</a>
</body>
</html>
6.insert.jsp由controller层的 insert方法跳转
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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 src="<%=path %>/state/js/jquery.min.js" language="javascript"></script>
<script type="text/javascript">
// 控制onsubmit提交的方法,方法名是vform()
function vform(){
//获取下面的id值
var ln = $("#name").val();
var lp = $("#age").val();
//判断上面的变量,如果为空字符串不能提交
if(ln == ""){
alert("请输入登录名!");
return false;
}
if(lp == ""){
alert("请输入密码!");
return false;
}
//除以上结果的可以提交,返回true
return true;
}
</script>
</head>
<body>
path:<%=basePath %>
<!-- 用onsubmit调用上面的方法 -->
<form action="<%=path %>/user/insert" method="post" onsubmit="return vform()">
<table width="100" border="1">
<tr>
<th>名字</th>
<th>年龄</th>
</tr>
<tr>
<td><input type="text" id="name" name="name"/></td>
<td><input type="text" id="age" name="age"/></td>
</tr>
</table>
<input type="submit" value="提交">
${inserUser}<br>
<a href="<%=path %>/user/list">返回</a>
</form>
</body>
</html>
7.delete.jsp提醒删除成功页面,由controller层delete方法跳转
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!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>
<style type="text/css">
div{text-align: center;}
div{height: 50px;width: 200px}
</style>
</head>
<body>
<div>
${deleteUser }<br>
<a href="<%=path %>/user/list">返回</a>
</div>
</body>
</html>
8.update.jsp修改 ,修改之前先要进行查询id注意不要忘记把controller层,
把update查询出来的id在这里遍历,放到隐藏那个文本标签里,然后在给个name属性个值,在value里放入遍历出来的id值
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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 src="<%=path %>/state/js/jquery.min.js" language="javascript"></script>
<script type="text/javascript">
// 控制onsubmit提交的方法,方法名是vform()
function vform(){
//获取下面的id值
var ln = $("#name").val();
var lp = $("#age").val();
//判断上面的变量,如果为空字符串不能提交
if(ln == ""){
alert("请输入登录名!");
return false;
}
if(lp == ""){
alert("请输入密码!");
return false;
}
//除以上结果的可以提交,返回true
return true;
}
</script>
</head>
<body>
path:<%=basePath %>
<!-- 用onsubmit调用上面的方法 -->
<form action="<%=path %>/user/update" method="post" onsubmit="return vform()">
<c:forEach items="${uid}" var="cc">
<input type="text" name="id" value="${cc.id }"/>
<table width="100" border="1">
<tr>
<th>名字</th>
<th>年龄</th>
</tr>
<tr>
<td><input type="text" id="name" name="name"/></td>
<td><input type="text" id="age" name="age"/></td>
</tr>
</table>
</c:forEach>
<input type="submit" value="提交">
${updateUser}<br>
<a href="<%=path %>/user/list">返回</a>
</form>
</body>
</html>
以上代码就是一个完整的ssm.