昨天拿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. 【Kill】两条Linux命令彻底杀死Oracle

    今天编写的两条极具杀伤力的命令,它可以瞬间将Oracle杀死在无形之中.后面我将给出简单注释并展示一下它的威力.$ ps -ef |grep $ORACLE_SID|grep -v grep|awk ...

  2. 转: vim简明教程

    vim的学习曲线相当的大(参看各种文本编辑器的学习曲线),所以,如果你一开始看到的是一大堆VIM的命令分类,你一定会对这个编辑器失去兴趣的.下面的文章翻译自<Learn Vim Progress ...

  3. HDU 1234 开门人和关门人

    #include <string> #include <algorithm> #include <iostream> using namespace std; st ...

  4. [Django实战] 第8篇 - 分页列表

    当用户登录成功后,首先看到的是他自己之前提交的任务列表,本篇将实现该页面. 视图(views.py)里定义如下: from django.core.paginator import Paginator ...

  5. SQL执行效率总结

    1.关于SQL查询效率,100w数据,查询只要1秒,与您分享: 机器情况 p4: 2.4 内存: 1 G os: windows 2003 数据库: ms sql server 2000 目的: 查询 ...

  6. iOS开发之第三方登录微博-- 史上最全最新第三方登录微博方式实现

    相关资源地址: 本项目demo地址 :  https://github.com/zhonggaorong/weiboSDKDemo 最新SDK下载:  最新微博SDK 官网注册地址:点击打开链接 最新 ...

  7. PHP开发中常见的安全问题详解和解决方法(如Sql注入、CSRF、Xss、CC等

    页面导航: 首页 → 网络编程 → PHP编程 → php技巧 → 正文内容 PHP安全 PHP开发中常见的安全问题详解和解决方法(如Sql注入.CSRF.Xss.CC等) 作者: 字体:[增加 减小 ...

  8. Xcode之外的文档浏览工具--Dash (在iOS代码库中浏览本帖)

    链接地址:http://www.cocoachina.com/bbs/read.php?tid=273479 Xcode之外的文档浏览工具--Dash    (在iOS代码库中浏览本帖)       ...

  9. python中的异常如何处理

    一.异常基础 在编程程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面. try: #正常逻辑代码 input = raw_input("输入数字:") data ...

  10. 条码知识之九:EAN-128条码(上)

     EAN-128码,现称GS1-128码,是专用于GS1系统中的条码,可以标注商品的附加信息,在商品信息的标识.产品的跟踪与追溯中有广泛的用途. EAN-128码来自于CODE-128码,在字符集.条 ...