ssm框架整合
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。经过一段时间的ssm框架学习,我初步掌握了ssm框架搭建的方法,下面以注册代码为例,对ssm框架进行了简单的实现。希望可以帮到你们!
1. 导入mybatis,spring,springmvc需要的jar包
2. 编写web.xml文件
- web.xml文件头
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
</web-app>
- 配置spring相关配置
<!-- spring -->
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 配置springmvc相关配置
<!-- springmvc -->
<!-- 前端控制器 -->
<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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 配置字符编码过滤器
<!-- 字符编码过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 编写spring配置文件applicationContext.xml文件
第一种:
- 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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/context
http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byName">
</beans>
- 添加注解扫描
<!-- 注解扫描 -->
<context:component-scan base-package="com.xxx.service.impl"></context:component-scan>
- 添加数据源
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
<property name="username" value="root"></property>
<property name="password" value="数据库密码"></property>
</bean>
- 产生SQLSessionFactory对象
<!-- SqlSessionFactory -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 给哪个包下的类起别名 -->
<property name="typeAliasesPackage" value="com.xxx.pojo"></property>
</bean>
- 添加扫描器,扫描mapper
<!-- 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.mapper"></property>
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
根据需要添加事务管理器
<!-- 事务管理器 -->
<bean id="txManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 声明式事务 -->
<tx:advice id="txAdvice" transaction-manager="txManage">
<tx:attributes>
<tx:method name="ins*"></tx:method>
<tx:method name="del*"></tx:method>
<tx:method name="upd*"></tx:method>
<tx:method name="*" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<aop:pointcut expression="execution(* com.xxx.service.impl.*.*(..))" id="mypoint"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
</aop:config>
第二种:
- 使用外部数据库配置文件db.properties获取数据库连接
<!-- 注解扫描 -->
<context:component-scan base-package="com.xxx.service.impl"></context:component-scan>
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- SqlSessionFactory -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 给哪个包下的类起别名 -->
<property name="typeAliasesPackage" value="com.xxx.pojo"></property>
</bean>
- 配置扫描器时,如果使用外部数据库配置文件,需要修改为:
<!-- 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.czxy.mapper"></property>
<!-- 不使用用外部配置文件时 -->
<!-- <property name="sqlSessionFactory" ref="factory"></property> -->
<!-- 使用外部配置文件时 -->
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
- 外部数据库配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=用户名
jdbc.password=密码
- 事务管理器(与上面相同)
4. 编写springMVC配置文件springmvc.xml文件
- springMVC配置文件文件头
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
</beans>
- 添加注解扫描
<!-- 1、添加注解扫描器 -->
<context:component-scan base-package="com.xxx.controller"></context:component-scan>
- 添加注解驱动
<!-- 注解驱动,注册HaddlerMapping和HadllerAdapter -->
<mvc:annotation-driven></mvc:annotation-driven>
- 放行静态资源
<!-- 设置静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
若是上传文件,需要添加文件类
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
这里的id只能是:multipartResolver,否则会报错
在控制器中使用:
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(req.getServletContext().getRealPath("files"),file.getOriginalFilename())
);
} catch (IOException e) {
e.printStackTrace();
}
将文件保存到指定位置。
在jsp页面中:
<form action="insert" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
可以添加异常映射
<bean id="ExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
</props>
</property>
</bean>
5. 在com.xxx.pojo包下编写实体类
package com.xxx.pojo;
public class Users {
private int id;
private String username;
private String password;
private String photo;
public int getId() {
return id;
}
public void setId(int 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;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
6. 编写mapper文件,使用注解形式
package com.xxx.mapper;
import org.apache.ibatis.annotations.Insert;
import com.xxx.pojo.Users;
public interface UsersMapper {
@Insert("insert into users values(default,#{username},#{password},#{photo})")
int insUsers(Users users);
}
7. 编写service接口
package com.xxx.service;
import com.xxx.pojo.Users;
public interface UsersService {
int insUsers(Users users);
}
8. 编写service实现类service.impl
- 添加@Service,将该类交给spring容器管理
添加@Resource或@Autowire,进行装配XXXMapper,前面设置为ByName装配
package com.xxx.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xxx.mapper.UsersMapper;
import com.xxx.pojo.Users;
import com.xxx.service.UsersService;
@Service
public class UsersServiceImpl implements UsersService {
@Resource
private UsersMapper usersMapper;
@Override
public int insUsers(Users users) {
return usersMapper.insUsers(users);
}
}
9. 编写controller类
- 添加@Controller,将该类交给SpirngMVC容器管理 添加@Resource,自动装配XXXServiceImpl
添加@RequestMapping("/register"),请求映射
package com.xxx.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.xxx.pojo.Users;
import com.xxx.service.UsersService;
@Controller
public class UsersController {
@Resource
private UsersService usersServiceImpl;
@RequestMapping("/register")
public String register(Users users,MultipartFile file,HttpServletRequest req) {
String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String path = req.getServletContext().getRealPath("images")+"/"+fileName;
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
} catch (IOException e) {
e.printStackTrace();
}
//只能取到webapps文件内容
users.setPhoto(fileName);
int index = usersServiceImpl.insUsers(users);
if(index>0) {
return "/main.jsp";
}else {
return "redirect:/register.jsp";
}
}
}
10. 编写jsp页面(需要导入jquery库)
<%@ 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>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
var username = false;
var password = false;
var passwordSure = false;
//用户名
$(":text:eq(0)").blur(function() {
if($(this).val()==""){
$(this).next().css("color","red").html("X")
username=false;
}else{
$(this).next().css("color","green").html("√");
username = true;
}
});
//密码
$(":password:eq(0)").blur(function() {
//js中要求正则两则必须有//
if(!$(this).val().match(/^\w{6,12}$/)){
$(this).next().css("color","red").html("X")
password = false;
}else{
$(this).next().css("color","green").html("√");
password = true;
}
});
//确认密码
$(":password:eq(1)").blur(function() {
//js中要求正则两则必须有//
if($(this).val()=="" || ($(this).val() != $(":password:eq(0)").val())){
$(this).next().css("color","red").html("X")
passwordSure = false;
}else{
$(this).next().css("color","green").html("√");
passwordSure = true;
}
});
$(":submit").click(function () {
if(username==false || password == false || passwordSure == false || $(":file:eq(0)").val==""){
alert("请填写正确信息")
return false;
}
});
})
</script>
</head>
<body>
<form action="register" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"><span></span><br>
密码:<input type="password" name="password"><span></span><br>
确认密码:<input type="password" name="passwordSure"><span></span><br>
头像:<input type="file" name="file"><span></span><br>
<input type="submit" value="注册">
</form>
</body>
</html>
11、编写log4j.properties文件:
log4j.rootCategory=ERROR,CONSOLE,LOGFILE
log4j.logger.cn.czxy.mapper=DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss} %m %n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=D:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%m %n