昨天拿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. Hello China操作系统STM32移植指南(二)

    移植步骤详解 下面就以MDK 4.72为开发环境,详细说明Hello China内核向STM32的移植过程.MDK 4.72评估版只支持32K代码的编译,这对Hello China的内核来说,裁剪掉一 ...

  2. HDU 2719 The Seven Percent Solution

    #include <cstdio> #include <cstring> int main() { ]; ]!='#') { ; while (i<strlen(s)) ...

  3. Sicily-1438

    一.      题意 买二送一.排序之后隔三求和,求折扣的最大值. 二.      代码 // // main.cpp // sicily-1438 // // Created by ashley o ...

  4. Convert Sorted List to Binary Search Tree ------C++ 递归创建平衡二叉查找树

    有序链表 0->1->2->3->4->5 转换为一个二叉排序树.我们在此创建一个平衡二叉排序树 1.先找链表到中间的节点 2.中间节点的val创建一个新的树节点Tree ...

  5. Android清单文件具体解释(三)----应用程序的根节点&lt;application&gt;

    <application>节点是AndroidManifest.xml文件里必须持有的一个节点,它包括在<manifest>节点下.通过<application>节 ...

  6. TextBox控件只允许输入出生日期,并验证年龄不得小于18岁

    1.Body tag <form id="form1" runat="server"> <div> <asp:Label ID=& ...

  7. CSS的z-index(分层)

    z-index是针对网页显示中的一个特殊属性.因为显示器是显示的图案是一个二维平面,拥有x轴和y轴来表示位置属性.为了表示三维立体的概念如显示元素的上下层的叠加顺序引入了z-index属性来表示z轴的 ...

  8. [Swust OJ 799]--Superprime Rib(DFS)

    题目链接:http://acm.swust.edu.cn/problem/799/ Time limit(ms): 1000 Memory limit(kb): 10000   Description ...

  9. Python之路Day14

    主要内容:jQuery进阶.CSS伪类和伪元素.jQuery插件 tab菜单样式 checkbox全选.反选 位置:scrollTop和offset 事件:两种绑定事件的方式和委托delegate a ...

  10. Hbase split的过程以及解发条件

    一.Split触发条件   1.  有任一一个Hfile的大小超过默认值10G时,都会进行split    2.  达到这个值不在拆分,默认为int_max,不进行拆分       3.compact ...