The first SpringMVC program (configuration version and annotation version)

Configuration version

1. Create a new Moudle, springmvc-02-hello, and add web support!

2. Make sure to import the dependency of SpringMVC!

3. Configure web.xml and register DispatcherServlet

<?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.注册DispatcherServlet-->
   <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
       <!--启动级别-1-->
       <load-on-startup>1</load-on-startup>
   </servlet>

   <!--/ 匹配所有的请求;(不包括.jsp)-->
   <!--/* 匹配所有的请求;(包括.jsp)-->
   <servlet-mapping>
       <servlet-name>springmvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

4. Write SpringMVC configuration files! Name: springmvc-servlet.xml: [servletname]-servlet.xml

Explain that the name requirements here are according to the official

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

</beans>

5. Add processing mapper

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

6. Add a processor adapter

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

7. Add a view resolver

<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
   <!--前缀-->
   <property name="prefix" value="/WEB-INF/jsp/"/>
   <!--后缀-->
   <property name="suffix" value=".jsp"/>
</bean>

8. To write the business Controller we want to operate, either implement the Controller interface or add annotations; we need to return a ModelAndView, load data, and seal the view;

package com.kuang.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//注意:这里我们先导入Controller接口
public class HelloController implements Controller {
    
    

   public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
       //ModelAndView 模型和视图
       ModelAndView mv = new ModelAndView();

       //封装对象,放在ModelAndView中。Model
       mv.addObject("msg","HelloSpringMVC!");
       //封装要跳转的视图,放在ModelAndView中
       mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
       return mv;
  }
   
}

9. Give your own class to the SpringIOC container and register the bean

<!--Handler-->
<bean id="/hello" class="com.kuang.controller.HelloController"/>

10. Write the jsp page to be jumped to, display the data stored in ModelandView, and our normal page;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>

11. Configure Tomcat to start the test!

Possible problems: 404 appears during access, troubleshooting steps:

Check the console output to see if any jar packages are missing.

If the jar package exists and the display cannot be output, add the lib dependency in the IDEA project release!

Restart Tomcat to solve it!

Summary: Looking at this, it is estimated that most students can understand the principle, but we will not write this in actual development, otherwise it will be crazy, why do you still learn this stuff! Let's look at an annotated version implementation.

Annotated version

1. Create a new Moudle, springmvc-03-hello-annotation. Add web support!

2. Since Maven may have resource filtering problems, we will configure it perfectly

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

3. Introduce related dependencies in the pom.xml file: mainly Spring framework core libraries, Spring MVC, servlet, JSTL, etc. We have introduced it in the parent dependency!

4. Configure web.xml

important point:

<?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.注册servlet-->
   <servlet>
       <servlet-name>SpringMVC</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
       <!-- 启动顺序,数字越小,启动越早 -->
       <load-on-startup>1</load-on-startup>
   </servlet>

   <!--所有请求都会被springmvc拦截 -->
   <servlet-mapping>
       <servlet-name>SpringMVC</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

The difference between / and /*: <url-pattern> / </ url-pattern> will not match the .jsp, only for the requests we write; that is, the .jsp will not enter the Spring DispatcherServlet class. <url-pattern> /* </ url-pattern> will match *.jsp, and the DispatcherServlet class of spring will appear again when returning to the jsp view, causing the corresponding controller not to be found, so a 404 error is reported.

Pay attention to the issue of web.xml version, ask for the latest version!

Register DispatcherServlet

Associated SpringMVC configuration file

Startup level is 1

The mapping path is / [Do not use /*, it will 404]

5. Add the Spring MVC configuration file
Add the springmvc-servlet.xml configuration file under the resource directory. The configuration form is basically similar to the Spring container configuration. In order to support annotation-based IOC, the automatic scanning package function is set. 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">

   <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
   <context:component-scan base-package="com.kuang.controller"/>
   <!-- 让Spring MVC不处理静态资源 -->
   <mvc:default-servlet-handler />
   <!--
   支持mvc注解驱动
       在spring中一般采用@RequestMapping注解来完成映射关系
       要想使@RequestMapping注解生效
       必须向上下文中注册DefaultAnnotationHandlerMapping
       和一个AnnotationMethodHandlerAdapter实例
       这两个实例分别在类级别和方法级别处理。
       而annotation-driven配置帮助我们自动完成上述两个实例的注入。
    -->
   <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>

In the view resolver, we store all the views in the /WEB-INF/ directory, which can ensure the security of the view, because the files in this directory cannot be directly accessed by the client.

Let the IOC comments take effect

Static resource filtering: HTML. JS. CSS. Pictures, videos...

Annotation-driven MVC

Configure view resolver

6. Create Controller

Write a Java control class: com.kuang.controller.HelloController, pay attention to coding standards

package com.kuang.controller;

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

@Controller
@RequestMapping("/HelloController")
public class HelloController {
    
    

   //真实访问地址 : 项目名/HelloController/hello
   @RequestMapping("/hello")
   public String sayHello(Model model){
    
    
       //向模型中添加属性msg与值,可以在JSP页面中取出并渲染
       model.addAttribute("msg","hello,SpringMVC");
       //web-inf/jsp/hello.jsp
       return "hello";
  }
} 

@Controller is to allow the Spring IOC container to be automatically scanned when it is initialized;

@RequestMapping is to map the request path, here because there are mappings on the class and method, it should be /HelloController/hello when accessed;

The method declares the parameters of the Model type to bring the data in the Action to the view;

The result returned by the method is the name of the view hello, plus the prefix and suffix in the configuration file to become WEB-INF/jsp/hello.jsp.

7, create a view layer

Create hello.jsp in the WEB-INF/jsp directory, the view can directly retrieve and display the information brought back from the Controller;

The value or object stored in the Model can be retrieved through EL representation;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>SpringMVC</title>
</head>
<body>
${msg}
</body>
</html>

8. Configure Tomcat to run

Configure Tomcat, start the server, and access the corresponding request path!

OK, the operation is successful!

summary

The implementation steps are actually very simple:

Create a new web project

Import the relevant jar package

Write web.xml, register DispatcherServlet

Write springmvc configuration file

The next step is to create the corresponding control class, controller

Finally, improve the correspondence between the front-end view and the controller

Test run debugging.

Three things that must be configured to use springMVC:

Processor mapper, processor adapter, view resolver

Usually, we only need to manually configure the view parser, and the processor mapper and the processor adapter only need to enable the annotation driver, which saves a lot of xml configuration

Guess you like

Origin blog.csdn.net/david2000999/article/details/115264945