您的位置:首页 > 编程语言 > Java开发

Java web 之 Spring+Mybatis+Spring MVC框架整合(下)

2017-09-01 09:06 876 查看
前两篇,我们主要讲了聚合工程Maven的创建(通过Maven本地仓库,集中管理我们项目中的jar包),子Maven Project ssm-web 继承父Maven
Project  ssm-parent;ssm-web聚合项目中又创建了一个Maven Modulessm-web-test,打包方式为war包;以及Mybatis逆向工程的使用和Spring+Mybatis的整合,以及最后JUnit单元的调试;SSM整合系列到现在,只剩下最后一个关键人物还没有出场,那就是我们的
Spring MVC框架。

【聚合:很多节点合到一起的一个工程,但是每个节点不能独立存在。】



Spring MVC

开始之前,我们先来看一下MVC(一种设计模式)的大致流程图:



用户发出请求给控制器,控制器决定去调用哪个模型,模型中有不同的业务逻辑,然后Model层返回相应的数据给控制器,控制器调用视图,进行视图渲染和组织数据,最后,将呈现好的界面和数据返回给我们用户。

ok,以上是讲前预热,Now,我们开始我们的Spring MVC框架之旅。

首先,我们看下,目前我们的项目目录结构:



配置spring-MVC.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
<!-- 配置包扫描器 -->
<context:component-scan base-package="com.appleyk.controller"></context:component-scan>
<!-- 配置注解驱动 -->
<mvc:annotation-driven/>
<!-- 视图解析器  定义跳转的文件的前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 添加静态资源css、js映射文件 -->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
</beans>


上面,有几个地方需要注意一下,下图均已标注:



配置好MVC后,我们需要再配置一下整个项目的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>ssm-web-test</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- 初始化Spring容器 +Spring和Mybatis的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis/spring-mybatis.xml</param-value>
</context-param>

<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>

<!-- Spring MVC的前端控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<!-- DispatcherServlet:中央控制器,把请求给转发到具体的控制类 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, spring-MVC的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC/spring-MVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


上面有几个需要注意的敌法,如下图标注:





其他倒没什么,好了,到这里,我们的Spring MVC框架也整合进项目中了,我们跑一下整个项目,看下我们改动web.xml后,是否影响了我们整个web项目的走向:

小插曲(spring-MVC.xml的路径写错了):



所以,配置文件里面,涉及路径的地方,一定要检查检查再检查,这里,应该是

springMVC/spring-MVC.xml



 上述的web.xml里面,我已经更改了错误。改后,我们再次运行一下我们的web项目:



Good,我们SSM框架整合后的项目正常运行,最后看一眼index.jsp页面,真的是最后一眼:



到这,先别急着兴奋,因为我们还差一个重要的环节,那就是测试我们的Spring MVC框架,怎么测,请继续往下看:



我们想实现这样一个功能,浏览器中输入一个url请求,格式为/user/username,然后,我们将这个url中的username传递到一个jsp页面进行欢迎展示:

(1)、怎么跳到这个jsp页面呢?

当然是使用@controller注解的方式,return jsp,当然我们的spring-MVC.xml中已经给我们配置好了视图解析器的路径(/WEB-INF/views/),我们这里只需要返回一个包含jsp文件的名字就行。

(2)、怎么将这个username的值传递给jsp页面呢?

这里我们使用ModelAndView类实现,一看就知道,这个类含两个部分,一个是数据部分,一个是视图,因此,我们让控制器Controller返回一个ModelAndView对象,该对象同时包含了要跳转的页面showUser和要传递的数据username

好了,我们开始,走一遍Controller-->Model-->View,测试一下Spring MVC:

1、在/WEB-INF/views/下面,新建一个jsp文件,取名,showUser.jsp:



目前,showUser.jsp还未有任何内容输出,我们放到后面

2、在com.appleyk.controller包下面添加一个java文件UserController.java:

package com.appleyk.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;

@Controller
public class UserController {

@RequestMapping("/user/{userName}")
public ModelAndView Hello(@PathVariable String userName){

ModelAndView mad = new ModelAndView("showUser");
//将数据存入modelMap
mad.addObject("message", userName);
return mad;
}
}




上面一个"showUser",就能指向对应的jsp文件,有图有真相:



控制器的类我们写好了,现在差一个jsp前台页面展示,我们改一下我们的

showUser.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>appleyk的CSDN</title>
</head>
<body>
亲爱的${requestScope.userName},欢迎你!
</body>
</html>


我们用requestScope(表示变量能在本次请求中使用)拿到mad对象中的userName

Controller我们写好了,View我们也写好了,现在就是Model,我们还没有提供,这个数据来自于url请求中的userName,因此,我们需要先运行项目:

九月 01, 2017 1:39:32 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
信息: FrameworkServlet 'springMVC': initialization completed in 1219 ms
九月 01, 2017 1:39:32 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-bio-8080"]


tomcat启动成功,然后我们打开浏览器,输入:http://localhost:8080/user/appleyk



我们多试几个:





我们想一下,如果我们返回的是一个动态数据怎么做到?

我们依然使用url地址请求的方式

修改下UserController.java:

package com.appleyk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.appleyk.pojo.User;
import com.appleyk.service.UserService;

@Controller
public class UserController {

@RequestMapping("/user/{userName}")
public ModelAndView Hello(@PathVariable String userName){

ModelAndView mad = new ModelAndView("showUser");
//将数据存入modelMap
mad.addObject("message", userName);
return mad;
}

@Autowired
private UserService userservice;

@RequestMapping("/user/id/{userID}")
@ResponseBody
public User getUserById(@PathVariable int userID){
User user =userservice.getUserById(userID);
return user;
}
}
需要解释的地方下图标注:



我们运行项目后,浏览器输入http://localhost:8080/user/id/1:



我们可以找一下UserMapper.class所在的位置:



我们为ssm-web-test的pom.xml添加如下内容:

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>

需要注意的地方下图标注:



注意增加解决XXXMapper.xml不自动关联的内容 在什么位置上。好了,我们重新启动一下我们的web项目:

九月 01, 2017 6:51:59 下午 org.springframework.web.servlet.DispatcherServlet initServletBean

信息: FrameworkServlet 'springMVC': initialization completed in 1095 ms

九月 01, 2017 6:51:59 下午 org.apache.coyote.AbstractProtocol start

信息: Starting ProtocolHandler ["http-bio-8080"]

我们验证一下,我们的UserMapper.xml有没有和我们的class放在一起:



ok,xml关联的问题算是解决了。

我们重新在浏览器中输入http://localhost:8080/user/id/2:



哈哈,有意思吧,跟闯关一样,针对上面的问题,我们给我们的项目加个jar包依赖,在哪加? 当然是在ssm-web-test的pom.xml文件里加:



增加的内容:

<!-- Jackson Json处理工具包-->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
</dependency>


图片说明如下:



好了,到这,我们好像没什么要加的了,是吗?我们再一次运行我们的项目:

信息: FrameworkServlet 'springMVC': initialization completed in 1419 ms

九月 01, 2017 7:09:19 下午 org.apache.coyote.AbstractProtocol start

信息: Starting ProtocolHandler ["http-bio-8080"]

九月 01, 2017 7:09:28 下午 com.alibaba.druid.pool.DruidDataSource info

信息: {dataSource-1} inited

成功,我们重复浏览器的url请求操作:http://localhost:8080/user/id/1



我们再来试一下,其他人的信息:



没问题,很好,我们的Controller很完美的为我们返回了View+Model,我们再试试另外一个Controller行为(url请求):



非常好,到这,我们的SSM整合框架就全部完了,真是几经周转,吐血之作!虽然案例有点简单,但是整合的过程却一点不能马虎,漏了哪个环节,项目即刻崩掉,你想想,如果你不熟练,一个bug都够你折腾半天了。

最后附上整个项目的下载地址:项目下载

以及整个项目的图文操作文档下载地址:我去,不等了,刷新太慢了,去我的资源里找

结束语:

不积跬步无以至千里,不积小流无以成江海,

程序人生的精彩需要坚持不懈地积累!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐