自下而上整合SSM框架(表现层)

此篇为自下而上搭建SSM框架子篇,如果第一次看该系列,请先看总篇:自上而下的搭建SSM框架

前言

今天我们整合表现层,表现层相对复杂,因为涉及到和前台交互,不过也不用担心,我们分析一下其实也很简单

分析

表现层最主要的是和前台的交互,而交互的入口文件既是web.xml,传统的servlet技术又有很多弊端所以我们使用SpringMVC,SpringMVC简单说就是通过一个前端控制器DispatcherServlet去拦截所有请求分发给相应控制器操作,所以我们需要做就是以下步骤:

  1. 引入SpringMVC的jar
  2. 在web.xml中配置DispatcherServlet
  3. 配置spring-web.xml去管理控制层代码
  4. 测试

配置

引入SpringMVC的jar(多引入一个json工具类,用于测试返回前台json代码)

<!-- 4)表现层 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>

<!--json工具类-->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.8.7</version>
</dependency>

在web.xml中配置DispatcherServlet

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要加载的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml
        Mybatis - > spring -> springmvc -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
    <!-- 默认匹配所有的请求 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

在spring文件下,配置spring-web.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: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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 -->
    <mvc:annotation-driven />

    <!-- 因为在web.xml中配置/,拦截了所有请求,包括静态资源请求js,css,图片等,这样会造成找不到相应的资源,
        在这里专门配置对这些静态资源请求地址,转到/resources下 -->
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:default-servlet-handler />

    <!-- 3.定义视图解析器 例如返回/WEB-INF/html/hello.html 只需在控制器中返回hello即可 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/html/"></property>
        <property name="suffix" value=".html"></property>
    </bean>

    <!-- 防止乱码,在spring-mvc.xml文件中加入这段配置后,spring返回给页面的都是utf-8编码了 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.csdn.shop.controller" />
</beans>

测试

在项目下创建controller包,下创建一个AreaController.class类

package com.csdn.shop.controller;

import com.csdn.shop.entity.Area;
import com.csdn.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "shopArea")
public class AreaController {
    @Autowired
    private AreaService areaService;
    //地址
    @RequestMapping(value = "getAreaList", method = RequestMethod.GET)
    @ResponseBody  //返回JSON字符串 如果不加可直接返回返回视图
    public Map<String, Object> getAreaList() {
        //返回的map对象
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //区域的值应该从前台穿过来,这里就不写前台了
        Area area = new Area();
        area.setAreaName("石家庄");
        area.setCreateTime(new Date());
        try {
            areaService.insertArea(area);
            //插入成功
            modelMap.put("success", area);
        } catch (Exception e) {
            //插入失败
            modelMap.put("fail ", e.getMessage());
        }
        return modelMap;
    }
}

编写好之后启动tomcat,跳出hello World页,在上面地址后面加上/shopArea/getAreaList,访问

{"fail ":"自定义异常"}

返回了失败,看一下异常是自定义异常,原来是上一节为了测试事务,咱们自定义了一个异常,现在去代码把异常注掉,重新打开tomcat访问,返回

{"success":{"areaId":3,"areaName":"石家庄","createTime":1533051720730}}

查看数据库,插入成功,并且成功返回

疑问

查看返回Area类中areaId字段为3,记得咱们在controller中给Area赋值时,并没有添加id字段,但是插入成功后Area类中就有了id字段,为什么?再次,我们在之前插入过一个北京区域id是1,现在插入的第二条数据id怎么就是3了呢?2去哪了?

这两个问题不解答,作为一个课后思考,知道的同学回复到评论里。

猜你喜欢

转载自blog.csdn.net/weixin_42604515/article/details/81322738
今日推荐