SpringMVC:第一个程序(动力)

首先配置DispatcherServlet:

自定义读取配置文件的位置

pom.xml:引入依赖

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.beijingnode</groupId>
  <artifactId>ch01-hellow-springmvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<!--    servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

<!--    springmvc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
<!--      编码和编译和JDK版本-->
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

 web.xml:初始化配置

声明springmvc的核心对象、声明servlet-mapping

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

<!--    声明,注册springmvc的核心对象DispatcherServlet-->
    <servlet>
        <servlet-name>myweb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--        自定义springmvc读取的配置文件的位置-->
        <init-param>
            <!--springmvc的配置文件属性-->
            <param-name>contextConfigLocation</param-name>
            <!-- 指定自定义文件的位置-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

<!--        在tomcat启动后,创建Servlet对象
               load-on-startup:表示tomcat启动后创建对象的顺序,它的值是正数,数值越小 tomacat创建对象越早
-->
        <load-on-startup>1</load-on-startup>

    </servlet>

<!--    所有的*..do请求交给myweb中央处理器处理-->
    <servlet-mapping>
        <servlet-name>myweb</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

创建springmvc配置文件:声明注解扫描

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 https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"/>
</beans>

创建控制类:MyController:创建控制方法

package com.bjpowernode.controller;

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

/*
@Controller:创建处理器对象,对象放在springmvc容器中
位置:在类的上面  和spring中的@Service,@Component一样

能处理请求的都是控制器(处理器):MyController能处理请求,叫做后端控制器
 */
@Controller
public class MyController {
    /*
    处理用户的请求,springmvc中是使用方法来处理的:方法是自定义的,可以有多种返回值,多种参参数

    准备处理doSome方法处理some.do请求
    @RequestMappper:请求映射,作用是把一个请求地址和一个方法绑定在一起,一个请求指定一个方法处理
       属性:value是一个String,表示请求的url地址(do.some)
             value的值必须是唯一 的,不能重复使用,在使用时,推荐地址以 /开头
       使用RequestMapping修饰的方法可以处理请求的类似Servlet中的doGet doPost

       位置:在方法的上面或者在类的上面

       返回值:ModelAndView:表示本次请求的处理结果
             Model:数据,请求处理完成后,要显示给用户的数据
             View:视图,比如jsp等等
     */
    @RequestMapping(value = "/some.do")
    public ModelAndView doSome(){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("mgs","欢迎使用mvc开发");
        mv.addObject("fun","执行的是dosome方法");

        //指定视图的完整路径
        //框架对视图执行的forword操作,request.getRequestDisPatcher("/show.jsp").forward(..)
        mv.setViewName("/show.jsp");

        //返回mv
        return mv;

    }
}

运行服务器访问页面:index.jsp,发起*.do请求

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <h1>hellow word</h1>
  <p><a href="some.do">发起some.do请求</a></p>
</body>
</html>

请求处理,跳转的页面:show.jsp

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 19:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
 <h3>show.jsp,从request作用域中获取数据</h3>
  <h3>msg数据:${msg}</h3>
  <h3>fun数据:${fun}</h3>
</body>
</html>

运行服务器:

 

 

为了防止用户直接访问:webapp下的jsp页面,可以进行下面操作

 WEB-INF目录下的内容是不可直接访问的,对用户是不可见的,用户是无权访问的

在WEB-INF创建一个新的子目录:view,之后用户在进行访问会报404

创建目录之后,控制器中的跳转路径了也需要进行更改:

mv.setViewName("/WEB-INF/view/show.jsp"

配置视图解析器:

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 https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"/>

<!--    声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀:视图文件的路径-->
        <property name="prefix" value="/WEB-INF/view/"/>
        <!-- 后缀:视图文件的扩展名-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

MyController:

package com.bjpowernode.controller;

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

/*
@Controller:创建处理器对象,对象放在springmvc容器中
位置:在类的上面  和spring中的@Service,@Component一样

能处理请求的都是控制器(处理器):MyController能处理请求,叫做后端控制器
 */
@Controller
public class MyController {
    /*
    处理用户的请求,springmvc中是使用方法来处理的:方法是自定义的,可以有多种返回值,多种参参数

    准备处理doSome方法处理some.do请求
    @RequestMappper:请求映射,作用是把一个请求地址和一个方法绑定在一起,一个请求指定一个方法处理
       属性:value是一个String,表示请求的url地址(do.some)
             value的值必须是唯一 的,不能重复使用,在使用时,推荐地址以 /开头
       使用RequestMapping修饰的方法可以处理请求的类似Servlet中的doGet doPost

       位置:在方法的上面或者在类的上面

       返回值:ModelAndView:表示本次请求的处理结果
             Model:数据,请求处理完成后,要显示给用户的数据
             View:视图,比如jsp等等
     */
   // @RequestMapping(value = "/some.do")
    @RequestMapping(value = {"/some.do","/first.do"})   //value里面可以写多个名字进行访问
    public ModelAndView doSome(){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("mgs","欢迎使用mvc开发");
        mv.addObject("fun","执行的是dosome方法");

        //指定视图的完整路径
        //框架对视图执行的forword操作,request.getRequestDisPatcher("/show.jsp").forward(..)
       // mv.setViewName("/show.jsp");

        //mv.setViewName("/WEB-INF/view/show.jsp");//名字很长,可以通过视图解析器

        /*
        * 当配置了视图解析器后,可以使用逻辑名称(文件名),指定视图
        * 框架会使用视图解析器的前缀+逻辑名称+后缀组成完整的路径,这里就是字符连接操作
        * /WEB-INF/view/ + show + jsp
        * */
        mv.setViewName("show");

        //返回mv
        return mv;

    }

    //一个控制器中可以定义多个方法
    @RequestMapping(value = {"/other.do","/second.do"})   //value里面可以写多个名字进行访问
    public ModelAndView doOther(){
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("mgs","欢迎========使用mvc开发==============");
        mv.addObject("fun","执行的是dosome方法");
        mv.setViewName("other");

        //返回mv
        return mv;

    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <h1>hellow word</h1>
  <p><a href="some.do">发起some.do请求</a></p>
  <p><a href="other.do">发起some.do请求</a></p>
</body>
</html>

show.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 19:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
 <h3>/WEB-INF/view/show.jsp,从request作用域中获取数据</h3>
  <h3>msg数据:${mgs}</h3>
  <h3>fun数据:${fun}</h3>
</body>
</html>

other.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 19:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
 <h3>/WEB-INF/view/other.jsp,从request作用域中获取数据</h3>
  <h3>msg数据:${mgs}</h3>
  <h3>fun数据:${fun}</h3>
</body>
</html>

点击第一个:

 

从地址栏输入第一个方法访问路径的另一个名字

 

点击第二个:

 

 地址栏输入第二个方法访问的另外一个路径

 

在一个控制类中,通过不同的地址,访问同一个方法

也可以在一个类中创建多个方法,处理不同的请求:

比如做一个用户表 增删改查,做4个方法就行了,一个方法对应着一个操作,就不像跟以前一样了,写Servlet的时候,一般情况下一个Servlet对应一个方法,一个Servlert对应一个请求,写4个请求,需要写4个Servlet,而现在不用了,只要写4个方法就够了,这是方便之处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值