SpingMVC+Spring+MyBatis开发步骤详解
项目结构(基于MyEclipse)
一、环境搭建
- 创建JavaWeb项目
- 导入相关jar包
- 引入相关配置文件
二、初始化配置
在web.xml文件中配置Spring工厂监听器、SpingMVC核心类和SpringMVC配置解决post方式乱码的过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!-- Spring工厂监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- Spring配置文件的位置 -->
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<!-- SpringMVC核心类 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 通过SpringMVC的配置文件 加载SpringMVC的核心类 -->
<param-value>classpath:/dispatcher.xml</param-value>
</init-param>
<!-- 规定该类的加载时机 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!-- 规定URL的访问路径 必须以.do结尾 才能访问到控制器的方法 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 配置解决post方式乱码的过滤器 -->
<filter>
<filter-name>encode</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- 必须是encoding -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
三、DAO
- 创建表
- 创建实体类
- 定义DAO接口
- MyBatis的配置文件实现DAO接口
- 对Spring的配置文件进行配置
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<!-- 注解扫描 --> <!-- 不写*,避免与SpringMVC容器冲突 -->
<context:component-scan base-package="com.xpf.service"></context:component-scan>
<!-- 引入数据库连接的配置文件 -->
<context:property-placeholder location="classpath:com/xpf/config/db.properties"/>
<!-- 连接数据库 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!-- 配置连接数据库的相关参数 -->
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 为dataSource属性做依赖注入 -->
<property name="dataSource" ref="dataSource"/>
<!-- 给实体类起别名 -->
<property name="typeAliasesPackage" value="com.xpf.entity"/>
<!-- Mapper文件的注册 -->
<property name="mapperLocations">
<list>
<value>classpath:com/xpf/mapper/*Mapper.xml</value>
</list>
</property>
</bean>
<!-- Spring自动创建DAO接口的实现类对象 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定哪一个包下创建DAO接口实现类对象 -->
<property name="basePackage" value="com.xpf.dao"/>
</bean>
<!-- service层的事务控制 -->
<!-- 引出Spring的事务控制的额外功能类 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 控制事务需要连接 创建连接必须有连接数据库的相关参数 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 激活@Transactional -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
四、Service
- 定义Service接口
- 实现Service接口
package com.xpf.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.xpf.dao.AdminDAO;
import com.xpf.entity.Admin;
import com.xpf.service.AdminService;
@Service
@Transactional
public class AdminServiceImpl implements AdminService {
@Autowired
private AdminDAO adminDAO;
@Override
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public Admin login(String username, String password) {
return adminDAO.queryByUsernameAndPassword(username, password);
}
@Override
public void register(Admin admin) {
adminDAO.insert(admin);
}
}
DAO层和Service层详细开发详见Struts2+Spring+MyBatis
五、Controller
- 写Controller类(注册方法中有文件上传)
package com.xpf.controller;
import java.io.File;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.xpf.entity.Admin;
import com.xpf.service.AdminService;
@Controller
@RequestMapping("admin")
public class AdminController {
@Autowired
private AdminService adminService;
@RequestMapping("login")
public String login(String username,String password,String code,HttpSession session) throws Exception{
String validationCode = (String)session.getAttribute("validationCode");
if(validationCode.equals(code)){
Admin admin = adminService.login(username, password);
if(admin!=null){
session.setAttribute("admin", admin);
return "redirect:/employee/showAll.do";
}else{
return "redirect:login.jsp";
}
}else{
return "redirect:login.jsp";
}
}
//注册
@RequestMapping("register")
public String register(@RequestParam("upload")MultipartFile upload,Admin admin,HttpSession session,String code)throws Exception{
/*
* 文件上传
*/
if(!upload.isEmpty()){
//获取文件上传的路径
String path = session.getServletContext().getRealPath("/upload");
//在upload文件夹下 创建文件名与上传的文件名相同的文件
File file = new File(path+"/"+upload.getOriginalFilename());
//把上传的文件转移到刚创建的文件中
upload.transferTo(file);
}
/*
* 注册用户
*/
//取出session中的验证码
String validationCode = (String)session.getAttribute("validationCode");
if(validationCode.equals(code)){
admin.setPath("/upload/"+upload.getOriginalFilename());
adminService.register(admin);
session.setAttribute("admin", admin);
return "redirect:/employee/showAll.do";
}else{
return "/regist.jsp";
}
}
//登出
@RequestMapping("exit")
public String exit(HttpSession session){
session.invalidate();
return "redirect:/login.jsp";
}
}
- 书写拦截器类
package com.xpf.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.xpf.entity.Admin;
public class LoginInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
HttpSession session = request.getSession();
Admin admin = (Admin)session.getAttribute("admin");
if(admin!=null){
return true;
}
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
}
- 配置dispatcher.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: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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">
<!-- SpringMVC开发中 会使用@Controller注解开发控制器 -->
<context:component-scan base-package="com.xpf.controller"></context:component-scan>
<!-- 需要使用注解开发SpringMVC的URL解析器 -->
<mvc:annotation-driven/>
<!-- 配置文件上传视图解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<!-- 配置SpringMVC拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 需要拦截 -->
<mvc:mapping path="/employee/**"/>
<!-- 无需拦截 -->
<mvc:exclude-mapping path="/admin/**"/>
<!-- 配置拦截器 -->
<bean id="loginInterceptor" class="com.xpf.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
六、其他
jar包和配置文件
密码:pera