HelloSpringMVC注解版 HelloSpringMVC注解版实现步骤解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

HelloSpringMVC注解版 HelloSpringMVC注解版实现步骤解析

CodeHuba   2021-03-15 我要评论
想了解HelloSpringMVC注解版实现步骤解析的相关内容吗,CodeHuba在本文为您仔细讲解HelloSpringMVC注解版的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:HelloSpringMVC,注解版,下面大家一起来学习吧。

注解版步骤

新建一个module,添加web的支持

由于Maven可能存在资源过滤的问题,我们将配置完善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>

在pom.xml文件引入相关的依赖

主要有Spring框架核心库、SpringMVC、servlet、JSTL等,我们在父依赖中已经引入了!

配置web.xml

注意点:

  • 注意web.xml版本问题,要最新版;
  • 注册DispatcherServlet
  • 关联SpringMVC的配置文件
  • 启动级别为1
  • 映射路径为/【不要用/*】

配置springmvc配置文件和视图解析器

我们把所有视图都存放在/WEB-INF/目录下,可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。

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

  <!--自动扫描包 让指定包下的注解生效 由IOC容器统一管理-->
  <context:component-scan base-package="com.kuang.controller"/>

  <!--让spring mvc不处理静态资源 .css .js -->
  <mvc:default-servlet-handler/>

  <!--annotation-driven帮助我们自动完成handlermapper和adapter实例的注入-->
  <mvc:annotation-driven/>

  <!--视图解析器: 模版引擎 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</beans>

创建Controller

@Controller
@RequestMapping("/hello")
public class HelloController {
  //真实访问地址:项目名/hello/h1
  @RequestMapping("/h1")
  public String Hello(Model model){
 
    model.addAttribute("msg","Hello SpringMVC annotation!");
    return "hello"; //会被视图解析器处理
  }
}

创建视图层

视图可以直接取出并展示从Controller带回的信息,可以通过EL表示取出Model中存放的值或者对象;

配置Tomcat运行

小结

实现步骤其实很简单:

  • 新建一个web项目
  • 导入相关jar包
  • 编写web.xml,注册DispatcherServlet
  • 编写springmvc配置文件
  • 创建对应的控制类,controller
  • 完善前端视图和controller之前的对应
  • 配置tomcat,测试运行调试。

springMVC必须配置的三大件:

  • 处理器映射器
  • 处理器适配器
  • 视图解析器

通常只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,省去了大段的xml配置。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们