美文网首页
Spring MVC入门

Spring MVC入门

作者: 磊_5d71 | 来源:发表于2018-10-28 17:13 被阅读0次

SpringMVC核心组件

图片.png
图片.png
图片.png

SpringMVC实现流程

图片.png
图片.png
图片.png
图片.png

XML配置使用

1、SpringMVC基础配置
2、XML配置Controller,HandlerMapping组件映射
3、XML配置ViewResolver组件映射

基于xml配置案例

  • web.xml
<!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>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--指定SpringMVC文件的位置-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
  • 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">



    <!--配置HandlerMapping,将url请求映射到Handler-->
    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <!--配置mapping-->
        <property name="mappings">
            <props>
                <!--配置test请求对应的handler-->
                <prop key="/test">testHandler</prop>
            </props>
        </property>
    </bean>

    <!--配置Handler-->
    <bean id="testHandler" class="com.alan.handler.MyHandler"></bean>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀-->
        <property name="prefix" value="/"></property>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>
  • MyHandler.java
package com.alan.handler;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyHandler implements Controller {
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        //装载模型数据和逻辑视图
        ModelAndView modelAndView = new ModelAndView();
        //添加模型数据
        modelAndView.addObject("name","TOM");
        //添加逻辑视图 ,在XML中通过配置前缀和后缀转换为/show.jsp
        modelAndView.setViewName("show");

        return modelAndView;
    }


}
  • show.jsp 直接打开获取不到TOM,需要通过/test访问DispatcherServlet处理后获取
package com.alan.handler;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyHandler implements Controller {
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        //装载模型数据和逻辑视图
        ModelAndView modelAndView = new ModelAndView();
        //添加模型数据
        modelAndView.addObject("name","TOM");
        //添加逻辑视图 ,在XML中通过配置前缀和后缀转换为/show.jsp
        modelAndView.setViewName("show");

        return modelAndView;
    }


}

通过注解方式配置

package com.alan.handler;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 *
 * 基于注解方式实现,不需要实现Controller
 */
@Controller("annotationHandler")
public class AnnotationHandler {


    /**
     * 业务方法一:ModelAndView完成数据的传递,视图的解析
     */

    @RequestMapping("/modelAndViewTest")
    public ModelAndView modelAndViewTest(){
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //填充数据
        modelAndView.addObject("name","ALAN");
        //设置逻辑视图
        modelAndView.setViewName("show");
        return modelAndView;
    }


    /**
     * 业务方法二:Model传值,String进行视图解析
     */

    @RequestMapping("/modelTest")
    public String modelTest(Model model){

        //填充模型数据
        model.addAttribute("name","cat");
        //设置逻辑视图
        return "show";
    }

    /**
     * 业务方法三:Map传值,String进行视图解析
     */

    @RequestMapping("/mapTest")
    public String mapTest(Map<String,String> map){
        //填充模型数据
        map.put("name","baobao");
        //设置逻辑视图
        return "show";
    }

}

案例

  • web.xml
<!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>



  <!--处理中文乱码-->
  <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>



  <!--配置调度servlet-->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--指定SpringMVC文件的位置-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--设置访问静态资源-->

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
  </servlet-mapping>

</web-app>
  • 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"
       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">



    <!--&lt;!&ndash;配置HandlerMapping,将url请求映射到Handler&ndash;&gt;-->
    <!--<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">-->
        <!--&lt;!&ndash;配置mapping&ndash;&gt;-->
        <!--<property name="mappings">-->
            <!--<props>-->
                <!--&lt;!&ndash;配置test请求对应的handler&ndash;&gt;-->
                <!--<prop key="/test">testHandler</prop>-->
            <!--</props>-->
        <!--</property>-->
    <!--</bean>-->

    <!--&lt;!&ndash;配置Handler&ndash;&gt;-->
    <!--<bean id="testHandler" class="com.alan.handler.MyHandler"></bean>-->

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀-->
        <property name="prefix" value="/"></property>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置自动扫描-->
    <context:component-scan base-package="com.alan.handler"></context:component-scan>
</beans>
  • handler

    /**
     * 添加商品并展示
     */
    @RequestMapping("/addGoods")
    public ModelAndView addGoods(Goods goods){
        //form表单中属性的名称和实体类中属性的名称对应以后,SpringMVC就会进行自动封装。
        System.out.println(goods.getName()+"---"+goods.getPrice());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("Goods",goods);
        modelAndView.setViewName("show");
        return modelAndView;

    }

  • add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>add</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        body{
            overflow-x:hidden;
        }
    </style>
</head>
<body>
<form class="form-horizontal" role="form" action="/addGoods" method="post">
    <div class="form-group">
        <label class="col-sm-1 control-label">名称</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="name" placeholder="请输入商品名称">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-1 control-label">价格</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="price" placeholder="请输入商品价格">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-1 col-sm-3">
            <button type="submit" class="btn btn-default">提交</button>
        </div>
    </div>
</form>
</body>
</html>
  • show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
    商品名称:${Goods.name} <br />
    商品价格:${Goods.price}
</body>
</html>

相关文章

网友评论

      本文标题:Spring MVC入门

      本文链接:https://www.haomeiwen.com/subject/fpljtqtx.html