【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】

这篇具有很好参考价值的文章主要介绍了【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

2024.3.4 Monday

Following the section 【WEEK1】 【DAY5】First MVC Program: Configuration File【English Version】

3.2. Using Annotations (not required for practical use as per section 3.1)

3.2.1. Create a new module named springmvc-03-hello-annotation and add web support

3.2.2. As Maven may have issues with resource filtering, we refine the configuration (web-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">
    <parent>
        <artifactId>SpringMVC_try1</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmvc-03-hello-annotation</artifactId>

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

    <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>

</project>

3.2.3. Introduce related dependencies in the pom.xml file

  • Mainly includes core libraries of Spring framework, Spring MVC, servlet, JSTL, etc.
    (Already included in the parent dependency: only check the Dependencies in the Maven sidebar)

3.2.4. Configure web.xml

  1. Add web support (see W1D2 1.3 Establish a module named springmvc-01-servlet, add support for Web app)
  2. Add lib dependencies (see W1D5 3.1.8. Configure Tomcat, Start Testing)
  3. Modify web-WEB-INF-web.xml
<?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">

    <!--1. Register servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Associate SpringMVC configuration file location through initialization parameters -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
            <!--     springmvc-servlet.xml file configuration is still required       -->
        </init-param>
        <!-- Load order, the smaller the number, the earlier it starts -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- All requests will be intercepted by SpringMVC -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
  1. Points to note
  • The difference between / and /: < url-pattern > / </ url-pattern > does not match .jsp, it only targets our written requests; that is, .jsp does not enter Spring’s DispatcherServlet class. < url-pattern > / </ url-pattern > matches *.jsp, which will result in the .jsp view entering Spring’s DispatcherServlet class again, leading to a 404 error because the corresponding controller cannot be found.
  • Pay attention to the web.xml version, it must be the latest!
  • Register the DispatcherServlet
  • Associate the SpringMVC configuration file
  • Set the startup level to 1
  • Map the path to / 【Do not use /*, it will cause 404】

3.2.5. Add SpringMVC Configuration File

  1. Create a new springmvc-servlet.xml configuration file in the resource directory
    【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】,# SpringMVC学习,mvc,学习
    【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】,# SpringMVC学习,mvc,学习
    The configuration is similar to that of the Spring container. To support IOC based on annotations, the package scanning feature is set up. The specific configuration information is as follows:
<?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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- Automatically scan packages, so that annotations in the specified package can take effect, managed by the IOC container -->
    <!-- If you want the annotations to be effective, you need to register an additional package in the java folder (as named in the next line within double quotes com.kuang.controller) -->
    <context:component-scan base-package="com.kuang.controller"/>

    <!-- To prevent Spring MVC from handling static resources -->
    <!-- Usually, some resources are referred (suffix is like .css, .js, .html, .mp3, .mp4) -->
    <!-- The following line is the default code for resource exclusion (standard syntax) -->
    <mvc:default-servlet-handler />

    <!--
    Support MVC annotation-driven development
        In Spring, the @RequestMapping annotation is commonly used for mapping relationships
        To make @RequestMapping annotation effective
        It is necessary to register DefaultAnnotationHandlerMapping
        And an AnnotationMethodHandlerAdapter instance in the context
        These two instances respectively handle on the class and method levels.
        And annotation-driven configuration automatically helps us inject these two instances.
     -->
    <mvc:annotation-driven />

    <!-- View Resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- Prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- Suffix -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>
  1. Attention
  • In the view resolver, we place all views in the /WEB-INF/ directory to ensure their security, since the files in this directory cannot be directly accessed by clients.
  • Enable IOC annotations
  • Static resource filtering: HTML, JS, CSS, images, videos, etc.
  • MVC annotation-driven
  • Configuring view resolver

3.2.6. Create View Layer

  1. Create a ->jsp folder under web->WEB-INF, then create a file named hello.jsp
    【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】,# SpringMVC学习,mvc,学习
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title Appears Here</title>  <!--Displayed on the tab-->
</head>
<body>
${msg}
</body>
</html>

Reference link: HTML中的head和body标签及作用
2. EL Expressions
Expression Language can retrieve values or objects stored in the Model.
EL表达式

3.2.7. Create HelloController

  1. Create a file named HelloController.java in the src->main->java->com->kuang->controller folder
    【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】,# SpringMVC学习,mvc,学习
package com.kuang.controller;

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

@Controller //Automatically assembled into the 15th line of springmvc-servlet.xml
//@RequestMapping("/hello0")//If the address is written here, then all the following continue to concatenate the specific path under this address

public class HelloController {

    // This is a request mapping, if you want multiple requests, you need to write multiple methods (from the start of @RequestMapping() until the method ends)
    //If the 8th line takes effect, then the real path would be localhost:8080/hello0/hello
    @RequestMapping("/hello")   //The real access address "project name->HelloController->hello": This is to jump to hello.jsp
    public String hello(Model model){
        //Encapsulate data: add attribute 'msg' with value to the model, which can be retrieved and rendered in the JSP page
        model.addAttribute("msg","Hello, SpringMVC Annotation");

        return "hello"; //After being assembled into springmvc-servlet.xml, it will be processed by the view resolver
    }

}
  1. Explanation
  • @Controller is for Spring IOC container to automatically scan at initialization;
  • @RequestMapping is for mapping the request path, since both the class and the method have mappings, the access path should be /HelloController/hello;
  • Declaring a parameter of type Model in the method is to carry the data from the Action to the view;
  • The result returned by the method is the name of the view ‘hello’, which becomes WEB-INF/jsp/hello.jsp with the prefix and suffix in the configuration file.

3.2.8. Configure Tomcat to Run

See W1D5 3.1.8. Configure Tomcat, Start Testing, launch the server, and access the corresponding request path.
http://localhost:8080/springmvc_03_hello_annotation_war_exploded/hello
【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】,# SpringMVC学习,mvc,学习文章来源地址https://www.toymoban.com/news/detail-839523.html

3.2.9. Summary

  1. Implementation Steps
  • Create a new web project
  • Import relevant jar packages
  • Write web.xml, register DispatcherServlet
  • Write springmvc configuration file
  • Next, create the corresponding controller classes
    -Finally, perfect the correspondence between the front-end view and the controller
  • Test, run, and debug
  1. The three essentials of using springMVC that must be configured
  • Handler mapper, handler adapter, view resolver
  • Usually, we only need to manually configure the view resolver, while the handler mapper and handler adapter can be activated simply by enabling annotation-driven, thus eliminating lengthy xml configuration

到了这里,关于【WEEK2】 【DAY1】The First MVC Program Using Annotations【English Version】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • HGame 2023 Week2 部分Writeup

    文章将第二周比赛结束后发布于我的博客:https://blog.vvbbnn00.cn/archives/hgame2023week2-bu-fen-writeup 第二周的解题过程中,遇到的不少有意思的题目,同时,也学习到了不少的知识,故书写此题解,作为记录。 Week2 比赛地址:https://hgame.vidar.club/contest/3 顾名思义,是一道Git泄露题,使

    2023年04月19日
    浏览(52)
  • NewStarCTF 2023 公开赛道 WEEK2|Crypto

    T1.滴啤 T2.不止一个pi T3.halfcandecode T4.Rotate Xor T5.broadcast T6.partial decrypt     下载题目附件,我们获得到以下代码。      观察代码得到,这是一道DP泄露题。面对DP泄露题的破解关注点就在于 对于各个数学关系的利用 。大体证明流程如下。        , 那么,我们可以获得    

    2024年02月06日
    浏览(53)
  • [HNCTF 2022 WEEK2]easy_include 文件包含遇上nginx

    这道纯粹记录 完全没想到 存在文件包含漏洞 过滤 data 等常见利用协议 然后我们看看能读取啥东西 发现啥都可以 那我们通过 这里泄露了中间件 那么我们直接去搜 发现存在一个文件日志包含漏洞 看了看就是会解析php 所以直接传递参数即可传递一个phpinfo 成功执行 那么就直

    2024年02月06日
    浏览(48)
  • 吴恩达机器学习week2实验答案Practice Lab Linear Regression【C1_W2_Linear_Regression】

    Exercise 1 Complete the compute_cost below to: Iterate over the training examples, and for each example, compute: The prediction of the model for that example f w b ( x ( i ) ) = w x ( i ) + b f_{wb}(x^{(i)}) = wx^{(i)} + b f w b ​ ( x ( i ) ) = w x ( i ) + b The cost for that example c o s t ( i ) = ( f w b − y ( i ) ) 2 cost^{(i)} = (f_{wb} - y^{(i)})^

    2024年02月09日
    浏览(42)
  • Creating my first web page using Angular

            Angular is a popular open-source framework for building web applications. Here are some basic concepts and knowledge about Angular: 1. TypeScript : Angular is built with TypeScript, a superset of JavaScript that adds static typing and other features to enhance development. 2. Components : Angular applications are built using components, which

    2024年02月14日
    浏览(46)
  • Angular(一) Creating my first web page using Angular

            Angular is a popular open-source framework for building web applications. Here are some basic concepts and knowledge about Angular: 1. TypeScript : Angular is built with TypeScript, a superset of JavaScript that adds static typing and other features to enhance development. 2. Components : Angular applications are built using components, which

    2024年02月08日
    浏览(38)
  • The injection point has the following annotations: - @org.springframework.beans.factory.annotation.

    Spingboot项目启动时报一下错误,错误如下: 报错大概意思就是,无法找到对应的dao接口,经过分析发现,未设置保扫描 解决方案如下:在启动类上加入以下代码即可

    2024年02月03日
    浏览(41)
  • 解决The injection point has the following annotations:@org.springframework.beans.factory.annotation错误~

    错误描述如下所示: 错误原因:未将 com.reggie.service.EmployeeService 类型的bean进行自动装配 我的错误原因是忘记给EmployeeService的实现类添加注解@Service,也就是未实现自动装配,那么只需要添加注解即可解决该问题

    2024年01月20日
    浏览(48)
  • Java 基本知识——first day

    注释不会被执行,是写给看代码的人看的。 单行注释 多行注释 文档注释 Java常见的 考点 总结四个点: 首字母应该以字母、$、_开始; 开始后可以任意字符; 不可用 大小写敏感   强类型语言 比如Java、C++、C 变量定义严格,先定义才能使用。 弱类型语言 比如

    2024年02月07日
    浏览(45)
  • 计算机网络学习first day

    In the first day.  首先,我们要先有清晰地学习思路,然后介绍计算机网络的发展及在信息时代的各类应用及带来的一些负面问题。然后是对因特网进行概述,包括网络,互联网和因特网的相关概念,因特网发展的三个历史阶段,因特网的标准化和管理机构,因特网的组成(边

    2024年01月19日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包