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

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

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

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

零:修改后的结构




一:修改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' );









SpringMVC入门二: 1规范结构, 2简单整合MyBatis的更多相关文章

  1. springMVC入门二

    一.准备工作 参考springMVC入门一,搭建maven项目如下: 前台结构如下: 项目介绍:使用springMVC实现前后台数据交互,例如controller返回json,页面传入pojo 二.具 ...

  2. SpringMVC入门二:SSM整合(spring+springmvc+mybatis)

    一.编程步骤 1.引入依赖 spring.springmvc.mybatis.mybatis-spring.mysql.druid.log4j.servlet-api.jstl.fastjson 2. ...

  3. SpringBoot2.0之四 简单整合MyBatis

    从最开始的SSH(Struts+Spring+Hibernate),到后来的SMM(SpringMVC+Spring+MyBatis),到目前的S(SpringBoot),随着框架的不断更新换代,也为 ...

  4. springMvc 入门二

    目的:请求参数接受,输出,常见的注解(在上一篇入门1基础上) 1:请求参数的绑定 1.1绑定的机制 表单中请求参数都是基于key=value的. SpringMVC绑定请求参数的过程是通过把表单提交请 ...

  5. SpringMvc入门二----HelloWorld

    1. 导入需要的架包: 2. 配置web.xml,添加Servlet <servlet> <servlet-name>springmvc</servlet-name> ...

  6. <SpringMvc>入门二 常用注解

    1.@RequestMapping @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME ...

  7. SpringMVC入门 bug集锦X3和SSM原始整合

  8. spring-boot-redis-cluster简单整合例子

    代码地址如下:http://www.demodashi.com/demo/13184.html 一.前言 spring-boot项目整合redis很常见,Redis 一般上生产的时候都是以集群模式部署 ...

  9. Java开发学习(二十三)----SpringMVC入门案例、工作流程解析及设置bean加载控制

    一.SpringMVC概述 SpringMVC是隶属于Spring框架的一部分,主要是用来进行Web开发,是对Servlet进行了封装.SpringMVC是处于Web层的框架,所以其主要的作用就是用来 ...

随机推荐

  1. Linux 动态库剖析

    进程与 API 动态链接的共享库是 GNU/Linux® 的一个重要方面.该种库允许可执行文件在运行时动态访问外部函数,从而(通过在需要时才会引入函数的方式)减少它们对内存的总体占用.本文研究了创建和 ...

  2. 一个最简的 USB Audio 示例

    经过了两三个月的痛苦,USB 协议栈的 Audio Device Class 框架已具雏形了,用了两三天时间,使用这个框架实战了一个基于新唐 M0 的最简单的 USB Audio 程序,可以作为 US ...

  3. 针对PCB飞针测试快速有效的技巧

    测试探针通过多路传输(multiplexing)系统连接到驱动器(信号发生器.电源供应等)和传感器(数字万用表.频率计数器等)来测试UUT上的元件.当一个元件正在测试的时候,UUT上的其它元件通过探针 ...

  4. cout输出各种进制

    cout使用: int main(){ int a=10;  cout<<"Dec:"<<a<<endl;  cout<<hex&l ...

  5. nodejs--express开发个人博客(2)

    上一部分已经实现了视图的雏形,现在加上逻辑操作. 登陆.注册.文章发表都需要用到数据库的数据存取,用的比较多的就是mongodb了. MongoDB 是一个对象数据库,它没有表.行等概念,也没有固定的 ...

  6. [置顶] java 枚举

    1. 什么是枚举?枚举就是用来存放一组固定的常量. 2. 枚举有什么作用?一些程序在运行时,它需要的数据不能是任意的,而必须是一定范围内的值:例如性别  男和女. public enum Gender ...

  7. perl5 第八章 子程序

    第八章 子程序 by flamephoenix 一.定义二.调用  1.用&调用  2.先定义后调用  3.前向引用  4.用do调用三.返回值四.局部变量五.子程序参数传递  1.形式  2 ...

  8. BZOJ 1089 严格n元树 (递推+高精度)

    题解:用a[i]表<=i时有几种树满足度数要求,那么这样就可以递归了,a[i]=a[i-1]^n+1.n个节点每个有a[i-1]种情况,那么将其相乘,最后加上1,因为深度为0也算一种.那么答案就 ...

  9. 过拟合/欠拟合&logistic回归等总结(Ng第二课)

    昨天学习完了Ng的第二课,总结如下: 过拟合:欠拟合: 参数学习算法:非参数学习算法 局部加权回归 KD tree 最小二乘 中心极限定律 感知器算法 sigmod函数 梯度下降/梯度上升 二元分类 ...

  10. Flex控件初始化问题

    有个对话框mx:TitleWindow->mx:TabNavigator->里有两个mx:Tile,每个Tile里都有个datagrid.测试如下:1.对话框显示后,马上动态监测第二个ti ...