SpringMVC入门二: 1规范结构, 2简单整合MyBatis

时间:2023-03-08 16:52:18
SpringMVC入门二: 1规范结构, 2简单整合MyBatis

昨天拿springMVC写的helloworld结构不好,

这次先调整一下体系结构 , 然后简单整合一下MyBatis

spring的配置还是以注解为主, 不过MyBatis的映射文件什么的还是拿xml写比较清楚

还是暂时先记下来, 然后再慢慢改吧

零:修改后的结构

SpringMVC入门二: 1规范结构, 2简单整合MyBatis




一:修改spring结构

这部分只说spring的配置, MyBatis的整合留到后一节细说

1.web.xml

这个还是在WEB-INF下, 开头和结尾引用了俩配置文件

ApplicationContext.xml , ApplicationContext-servlet.xml

核心拦截器指定了<url-pattern>*.html</url-pattern>就是硬性规定访问视图后缀为 .html
也就是说从url上看 返回的都是xxx.html , 就像struts处理过的 xxx.action或者xxx.do一样

比如:

<script type="text/javascript">
  //==>这里必须是 xx/xx.html ,因为spring定义的视图以html结尾
    document.location = "hello/helloWorld.html";
 </script>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!--==>1.定义spring加载资源的位置,默认为/WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:resources/spring/ApplicationContext.xml</param-value>
</context-param> <!--==>2.编码器 -->
<filter>
<filter-name>SetCharacterEncoding</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>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!--==>3.Spring上下文监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!--==>4.核心拦截器 -->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定资源位置: 名称-servlet.xml的配置(用于配置HandlerMapping和 HandlerAdapter) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:resources/spring/ApplicationContext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<!-- 硬性规定访问视图后缀为 .html -->
<url-pattern>*.html</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <session-config>
<session-timeout>20</session-timeout>
</session-config> </web-app>

2.ApplicationContext.xml

这个文件之前没有, 边都是和MyBatis相关的, 后一节详细说

3.ApplicationContext-servlet.xml

这个核心拦截器需要的配置, 指定注解的作用范围 , 所使用的视图解析器什么的

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="web.hello.*" /> <!-- HandlerMapping和HandlerAdapter的配置 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- 视图解析器的配置 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 上传下载配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
-->
</beans>

4.其他

src下分 resources(配置文件) 和 web(源代码) 俩文件夹
把Spring和MyBatis的配置文件都放在 src/resources 下( 编译完了都在 \WEB-INF\classes\resources里 )
MyBatis的Dao用mapper命名( 靠xml生成mapper的实现 )


二:整合MyBatis

lib中引入: mybatis-3.2.2.jar 和 mybatis-spring-1.2.0.jar


调用MyBatis的流程大概是:
请求 -> controller -> IService -> serviceImpl -> IMapper -> xml所生成的具体方法. 

之后再反向返回去直到view层

1.ApplicationContext.xml

根据jdbc.properties生成dataSource数据源
之后根据mybatis/config.xml生成 SessionFactory
最后一步比较有意思, src下Mapper文件夹( 相当于Dao )中 只定义接口 , 没有和它对应的实现( 没有DaoImpl )
而是让spring根据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:p="http://www.springframework.org/schema/p"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:resources/mybatis/jdbc.properties" /> <!--1.创建jdbc数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="url" value="${url}" />
</bean> <!-- 2.MyBatis的SessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:resources/mybatis/config.xml"/>
</bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean> <!-- 3.扫描 basePackage下所有的接口,根据对应的mapper.xml为其生成代理类-->
<!-- 这里的mapper都是接口, 让spring根据xml生成接口的具体实现 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="web.hello.mapper" />
</bean> </beans>

2.mybatis/config.xml

只是定义去哪找对应mapper的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <typeAliases>
<typeAlias type="web.hello.entity.User" alias="User"/>
</typeAliases> <mappers>
<mapper resource="web/hello/mapper/mapping/User.xml"/>
</mappers> </configuration>

3.User.xml

resultMap是定义一个返回数据的数据结构

<select id="listAllUser" 中的"listAllUser"就是 serviceImpl里调用的方法名

比如:
@Service(value = "userService")

@Transactional

public class UserServiceImpl implements IUserService

{


@Resource(name = "userMapper")


private UserMapper userMapper;

public List<User> getList() 


{

return userMapper.
listAllUser();
//==>这里直接调用xml中的定义 ,比较nb


}

}

<?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="web.hello.mapper.UserMapper"> <sql id="userColumns">uid,name,password,info</sql>
<!-- 定义返回数据的结构 -->
<resultMap type="User" id="userResultMap">
<id column="uid" property="uid"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
<result column="info" property="info"/>
</resultMap>
<!-- 相当于定义了一个实现方法 -->
<select id="listAllUser" resultMap="userResultMap">
select u.uid,u.name,u.password,u.info
from t_user u
</select>
<select id="getUserById" parameterType="int" resultMap="userResultMap">
select * from t_user u where u.uid = #{uid}
</select> <select id="getUserInfo" parameterType="User" resultMap="userResultMap">
select * from t_user where 1=1
<if test="name!=null and password!=null">
and name = #{name} and password=#{password}
</if>
<if test="uid!=null and uid>0">
and user_id = #{uid}
</if>
</select> </mapper>

4.整个调用流程

controller -> IService -> serviceImpl -> IMapper -> xml所生成的具体方法.

1)controller

package web.hello.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;//==>@Controller注解
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import web.hello.entity.User;
import web.hello.service.IUserService; @Controller
@RequestMapping(value="/hello")//==>指定命名空间:http://localhost:8080/HelloSpringMVC/hello
public class HelloController
{
@Resource(name = "userService")
private IUserService userService; //==>1.返回helloWorld字串
@RequestMapping(value="/helloWorld")//==>命名空间内具体请求: .../hello/helloWorld
public ModelAndView helloWorld(HttpServletRequest requset,HttpServletResponse response) throws Exception
{
System.out.println("==>start helloWorld()");
//==>ModelAndView是SpringMVC的一个核心对象org.springframework.web.servlet.ModelAndView;
ModelAndView mv = new ModelAndView();
mv.addObject("message", "==>Hello SpringMVC!"); //带参数,可以是Object
mv.setViewName("/view/hello"); //设置将要跳转的视图 return mv;
} //==>2.通过Dao返回List
@RequestMapping(value="/userList")
public ModelAndView getUserList(HttpServletRequest requset,HttpServletResponse response) throws Exception
{
System.out.println("==>start getUserList()"); List<User> list = this.userService.getList(); ModelAndView mv = new ModelAndView(); mv.addObject("resultList", list);
mv.setViewName("/view/userList"); return mv;
}
}

2).IService

package web.hello.service;

import java.util.List;

import web.hello.entity.User;

public interface IUserService
{
public List<User> getList();
}

3).serviceImpl

package web.hello.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import web.hello.entity.User;
import web.hello.mapper.UserMapper;
import web.hello.service.IUserService; @Service(value = "userService")
@Transactional
public class UserServiceImpl implements IUserService
{
@Resource(name = "userMapper")
private UserMapper userMapper; public List<User> getList()
{
return userMapper.listAllUser();
}
}

4).IMapper

package web.hello.mapper;

import java.util.List;
import org.springframework.stereotype.Repository; import web.hello.entity.User; @Repository(value = "userMapper")
public interface UserMapper
{
public User getUserById( Integer uid ); public List<User> listAllUser();
}

5) xml所生成的具体方法

最后是 3.User.xml中对应的
	<select id="listAllUser" resultMap="userResultMap">
select u.uid,u.name,u.password,u.info
from t_user u
</select>

之前都写过完整的了 不再重复了


6)去数据库里查询

CREATE TABLE t_user (
uid int(10) NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
password varchar(20) NOT NULL,
info varchar(20) DEFAULT NULL,
PRIMARY KEY (uid)
) insert into t_user values(1, 'rt' , '890307' , 'someinfo1' );
insert into t_user values(2, 'kk' , '890321' , 'someinfo2' );