EchoDemo's Blogs

springmvc学习笔记(9)-springmvc整合mybatis之controller

夜饮东坡醒复醉,归来仿佛三更。家童鼻息已雷鸣。敲门都不应,倚杖听江声。

长恨此身非我有,何时忘却营营。夜阑风静縠纹平。小舟从此逝,江海寄余生。

—-宋·苏轼《临江仙·夜饮东坡醒复醉》

配置springmvc.xml

在resources/spring文件下下创建springmvc.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-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- 对于注解的Handler 可以单个配置
    实际开发中建议使用组件扫描
    -->
    <!-- 可以扫描controller、service、...
    这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="com.echodemo.springmvcmybatis.controller"></context:component-scan>

    <!-- 注解的映射器 -->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>-->
    <!-- 注解的适配器 -->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->
    <!-- 使用mvc:annotation-driven代替上面两个注解映射器和注解适配的配置
     mvc:annotation-driven默认加载很多的参数绑定方法,
     比如json转换解析器默认加载了,如果使用mvc:annotation-driven则不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
     实际开发时使用mvc:annotation-driven
     -->
    <mvc:annotation-driven></mvc:annotation-driven>


    <!-- 视图解析器
    解析jsp,默认使用jstl,classpath下要有jstl的包
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp路径的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 配置jsp路径的后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app  version="2.3"
          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_3.xsd">
  <display-name>Archetype Created Web Application</display-name>

  <!-- 加载spring的容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
      若不配置,默认加载WEB-INF/servlet名称-servlet(springmvc-servlet.xml)
    -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--
    第一种:*.action,访问以.action结尾,由DispatcherServlet进行解析
    第二种:/,所有访问的地址由DispatcherServlet进行解析,对静态文件的解析需要配置不让DispatcherServlet进行解析,
            使用此种方式和实现RESTful风格的url
    第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet解析jsp地址,
            不能根据jsp页面找到handler,会报错
    -->
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

这个文件有两个作用:

(1)配置前端控制器(DispatcherServlet)

(2)加载spring容器:添加spring容器监听器,加载spring容器,使用通配符加载spring/下的配置文件:

applicationContext-dao.xml

applicationContext-service.xml

applicationContext-transaction.xml

编写Controller

package com.echodemo.springmvcmybatis.controller;

import com.echodemo.springmvcmybatis.bean.ItemsCustom;
import com.echodemo.springmvcmybatis.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    // 商品查询
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception{
        // 调用service查找数据库,查询商品列表,这里使用静态数据模拟
        List<ItemsCustom> itemsList = new ArrayList<>();
        itemsList = itemsService.findItemsList(null);
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 相当于request的setAttribute,在JSP页面中通过itemsList取数据
        modelAndView.addObject("itemsList", itemsList);
        // 指定视图
        modelAndView.setViewName("items/itemsList");
        System.out.println(modelAndView);
        return modelAndView;
    }
}

编写jsp

服务器路径为WEB-INF/jsp/items/itemsList.jsp。

<%@ page contentType="text/html;charset=UTF-8" language="java"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
    查询条件:
    <table width="100%" border=1>
        <tr>
            <td>
                <input type="submit" value="查询">
            </td>
        </tr>
    </table>
    商品列表:
    <table width="100%" border=1>
        <tr>
            <td>商品id</td>
            <td>商品名称</td>
            <td>商品价格</td>
            <td>商品描述</td>
            <td>操作</td>
        </tr>
        <c:if test="${not empty itemsList}">
            <c:forEach items="${itemsList}" var="item">
                <tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.price}</td>
                    <td>${item.detail}</td>
                    <td><a href="${pageContext.request.contextPath}/item/editItem.action?id=${item.id}" >修改</a></td>
                </tr>
            </c:forEach>
        </c:if>
    </table>
</form>
</body>
</html>

部署调试

1、idea上部署tomcat可以参考这里:springmvc学习笔记(1)-框架原理和入门配置-%E6%A1%86%E6%9E%B6%E5%8E%9F%E7%90%86%E5%92%8C%E5%85%A5%E9%97%A8%E9%85%8D%E7%BD%AE/)

2、启动之后访问:http://localhost:8080/springmvcmybatis/queryItems.action。大功告成。

🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------