【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
以用户管理系统的开发为例,详细介绍SpringMVC+Spring+Mybatis的整合,并在编写controller的过程中记录SpringMVC中的一些高级应用(会特别标示)
1. 项目整合搭建过程
1. 项目需求:主要实现简单的用户登录注册,以及修改自身信息功能,额外扩展一个用户管理系统,可以查看所有用户以及删除用户
2. 搭建工程:创建Maven工程
- 首先准备环境,mysql数据库、Spring的相关jar包、mybatis相关jar包,暂时只需要下图中的这些jar包,后面会逐步添加相关功能所需的jar包
- 整合SpringMVC+Spring+Mybatis,整合思路如下
- 第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
-
第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。
-
第三步:整合springmvc由于springmvc是spring的模块,不需要整合。
- 第一步:整合dao层
-
整合dao层
-
编写mybatis的配置文件,sqlmapconfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <!-- 配置分页插件,dialect指定使用的数据库类型 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>
- 编写applicationContext_dao.xml,将mybatis和spring进行整合:配置数据源、SqlSessionFactory、mapper扫描器
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- mybatis配置 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="password" value="${jdbc.password}"></property> <property name="username" value="${jdbc.name}"></property> </bean> <bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"></property> <property name="configLocation" value="classpath:conf/SqlMapConfig.xml"></property> </bean> <bean id="mfc" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="user_manage.mapper"></property> <property name="sqlSessionFactoryBeanName" value="ssf"></property> </bean> </beans>
- 逆向工程生成po类及mapper:对于单表查询使用mybatis逆向工程生成的mapper接口和对于的映射文件足够使用,也可以自己添加映射文件
import java.util.List; import org.apache.ibatis.annotations.Param; import user_manage.pojo.User; import user_manage.pojo.UserExample; public interface UserMapper { long countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer userAccount); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer userAccount); int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example); int updateByExample(@Param("record") User record, @Param("example") UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
-
- 整合service层:service层即业务层,在这里实现主要的处理逻辑代码
- 编写service层接口,以及接口实现类
import java.util.List; import user_manage.pojo.User; public interface UserService { public void insertUser(User user); public void deleteUser(int user_account); public List<User> findUserList(int pageNumber,int rows); public void updateUser(User user); }
- 将接口实现类扫描进Spring容器中,通过Spring进行管理,并创建applicationContext-service.xml,文件中配置扫描service。
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <context:component-scan base-package="user_manage.service"></context:component-scan> </beans>
-
配置开启事务管理:编写applicationContext_tx.xml,对service层中的所有方法开启事务管理
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- AOP配置 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* user_manage.service.*.*(..))"/> </aop:config> </beans>
- 编写service层接口,以及接口实现类
- 整合Controller层,编写SpringMVC配置文件:
- 创建springmvc.xml文件,配置处理器映射器、适配器和视图解析器,并配置扫描所有的controller类
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <context:component-scan base-package="user_manage.controller"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--该配置用于接收上传的文件--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>1048576</value> </property> <property name="defaultEncoding"> <value>utf-8</value> </property> </bean> <!--该配置用于处理RESTful风格路径所引起的访问静态资源路径错误问题--> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/html/" mapping="/html/**"/> </beans>
-
编写Controller类
-
编写jsp
- 加载spring容器:在web.xml中,将mapper、service、controller层的配置文件加载到spring容器中。并且配置前端控制器。
<?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>user_manage</display-name> <!-- 通过 controller、service、dao三层的配置文件加载spring容器,这里是spring应用上下文--> <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> <!-- RESTful风格的路径配置 --> <servlet> <servlet-name>RESTful</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--SpringMVC加载的配置文件,这里是springweb应用上下文 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>RESTful</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 以.do结尾的路径也会接收 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC加载的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- post请求编码过滤器,将post中的请求参数统一转为utf-8编码,/*表示拦截所有路径请求 --> <filter> <filter-name>postEncode</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>postEncode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- 创建springmvc.xml文件,配置处理器映射器、适配器和视图解析器,并配置扫描所有的controller类
- 源码可在我的github上下载:user_manage
2. 用户注册功能开发
1. 操作流程:首先进入注册页面,然后填写注册所需的数据,然后点击注册,发送请求
2. 开发Mapper:
<insert id="insertSelective" parameterType="user_manage.pojo.User">
<!-- 将自增主键生成的结果回写到传入的user_manage.pojo.User对象中 -->
<selectKey keyProperty="userAccount" keyColumn="user_account" order="AFTER" resultType="int">
select last_insert_id()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userAccount != null">user_account,</if>
<if test="userName != null">user_name,</if>
<if test="userPassword != null">user_password,</if>
<if test="userAge != null">user_age,</if>
<if test="userAddress != null">user_address,</if>
<if test="userTelephone != null">user_telephone,</if>
<if test="userImage != null">user_image,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userAccount != null">#{userAccount,jdbcType=INTEGER},</if>
<if test="userName != null">#{userName,jdbcType=VARCHAR},</if>
<if test="userPassword != null">#{userPassword,jdbcType=VARCHAR},</if>
<if test="userAge != null">#{userAge,jdbcType=INTEGER},</if>
<if test="userAddress != null">#{userAddress,jdbcType=VARCHAR}, </if>
<if test="userTelephone != null">#{userTelephone,jdbcType=CHAR},</if>
<if test="userImage != null">#{userImage,jdbcType=VARCHAR},</if>
</trim>
</insert>
3. 开发service:实现insertUser方法
public void insertUser(User user) {
userMapper.insertSelective(user);
}
4. 开发Controller:通过该开发了解@RequestMapping注解的部分特性、controller方法的返回值、参数绑定
- 关于@RequestMapping注解的部分特性:
- url映射:定义controller类中方法对应的url,进行处理器映射使用。
- 窄化请求映射路径:如果controller类中的每个方法都在同一级请求路径之下(根路径),那么就可以将根路径写在controller上,子路径写在方法上,最后匹配的路径就是根路径+子路径,这样做的好处就是如果controller中的方法很多,就不用重复的去相同的路径部分,减少代码量
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; /** * @ClassName:PageController * @Description:页面跳转,主要请求路径为/page/regist.do,不写.do是因为在前端控制器中配置扫描以.do结尾的请求路径 * 所以在RequestMapping中就不需要写.do */ @Controller @RequestMapping("/page") public class PageController { @RequestMapping("/regist") public ModelAndView toRegist(){ ModelAndView mv=new ModelAndView(); mv.setViewName("regist"); return mv; } }
- 限制http请求方法:出于安全性考虑,对http的请求方法限制。如果限制只接受post方式的请求,但进行get请求,则会报错
//限制只接受post和get方式的请求 @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
- 关于Controller方法的返回值:
- 返回ModelAndView:定义ModelAndView,将model和view分别进行设置,返回给前端控制器进行渲染和处理。
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public ModelAndView toRegist(){ ModelAndView mv=new ModelAndView(); mv.setViewName("regist"); return mv; }
- 返回String:如果controller方法返回string,有多重含义
- 表示返回逻辑视图名,所写值要考虑视图解析器中是否配置了前缀和后缀。真正视图(jsp路径)=前缀+逻辑视图名+后缀
//如果返回的String表示逻辑视图名,那么,只需要在方法的形参中添加一个Model类型的参数, //就会自动将Model对象和逻辑视图名代表的逻辑视图传给前端控制器进行处理,相当于返回ModelAndView @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; }
-
redirect重定向:redirect重定向特点就是浏览器地址栏中的url会变化。修改提交的request数据无法传到重定向的地址。因为重定向后重新进行request(request无法共享)
@Controller @RequestMapping("/page") public class PageController { //如果请求路径为/page,那么主动重定向跳转至注册页面 @RequestMapping("/") public String toPage(){ return "redirect:regist.do"; } @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; } }
-
forward页面转发:通过forward进行页面转发,浏览器地址栏url不变,request可以共享。
@Controller @RequestMapping("/page") public class PageController { //如果请求路径为/page,那么主动重定向跳转至注册页面 @RequestMapping("/") public String toPage(){ return "forward:regist.do"; } @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; } }
- 表示返回逻辑视图名,所写值要考虑视图解析器中是否配置了前缀和后缀。真正视图(jsp路径)=前缀+逻辑视图名+后缀
- 如果返回void:在controller方法形参上可以定义request和response,使用request或response指定响应结果
- 通过request进行页面转发,并传递参数
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public void toRegist(HttpServletRequest req,HttpServletResponse res){ req.setAttribute("key", "value"); try { req.getRequestDispatcher("path").forward(req, res); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
- 通过response页面重定向,无法传递参数,response.sendRedirect("url")
-
也可以通过response指定响应结果,例如html等,响应json数据如下:
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
- 通过request进行页面转发,并传递参数
- 返回ModelAndView:定义ModelAndView,将model和view分别进行设置,返回给前端控制器进行渲染和处理。
- 参数绑定:从客户端发送的请求中包括key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。
- 参数绑定默认支持的类型:直接在controller方法形参中定义这些类型的对象,就可以使用这些对象。因为在参数绑定过程中,控制器适配器如果遇到这些类型直接进行参数绑定。类型有HttpServletRequest、HttpServletResponse、HttpSession、Model/ModelMap(model是一个接口,modelMap是一个接口实现 ,可以将model数据填充到request域)
- 参数绑定默认支持的类型还包括Java中的简单类型(常用有String和8个基本类型):通过在形参前添加注解@RequestParam对简单类型的参数进行绑定,如果不使用@RequestParam,要求request传入参数名称(名称实际是key的值,request传入参数都是key/value,而且value都是字符串格式,所以需要转换器converters将字符串转为形参类型)和controller方法的形参名称一致,方可绑定成功(此外还要必须保证value值能够转换为形参类型,否则就会出现错误)。如果使用@RequestParam,不用限制request传入参数名称和controller方法的形参名称一致。通过required属性指定参数是否必须要传入,如果设置为true,通过defaultValue指定如果传入的值为空,则设置一个默认值,value就表示指定参数中的key名称
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model,@RequestParam(value="id",required=true,defaultValue="1") int id){ model.addAttribute("key", "value"); return "regist"; }
- 绑定pojo参数类型:如果形参类型为pojo类型,那么就必须满足一个规范,请求中传来的每一个key/value数据,每个数据的key都要与controller的pojo形参中的属性名称一致,那么就会将数据绑定到pojo对应的属性,如果不一致,那么请求中的数据就无法绑定到pojo对象的属性中
- 自定义一个converters转换器:将请求中的日期字符串转换为日期类型数据,这样就可以实现日期类型的参数绑定,如果绑定为pojo类型,即便pojo类型中包括非简单类型的属性,也需要对该属性的类型定义一个转换器,这样才能完成对pojo类的参数绑定。以实现java.util.Date的转换器为例
- 首先定义converters转换器类
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; //自定义转换器必须实现org.springframework.core.convert.converter.Converter接口 public class DateConvertor implements Converter<String,Date>{ @Override public Date convert(String source) { SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss"); Date date=null; try { date = sdf.parse(source); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return date; } }
- 将Converter配置装载进入SpringMVC的转换器集合中
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="user_manage.convertor.DateConvertor"></bean> </list> </property> </bean>
- 首先定义converters转换器类