学习SpringMVC的第一次项目HelloSpringMVC的代码实现

HelloSpringMVC

1.创建Maven项目并导入相关依赖。

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

2.修改web.xml文件


<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_3_1.xsd"
         version="3.1">

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            
            <param-value>classpath:springmvc-config.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

3.在resource目录下创建springmvc-config.xml并修改


<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">
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>

    
    <bean id="/hello" class="com.maple.controller.HelloController"/>

beans>

4.写Controller类

public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView模型和视图
        ModelAndView mv = new ModelAndView();
        //封装对象,放在ModelAndView中。
        mv.addObject("msg","HelloSpringMVC!!");
        //封装要转跳的视图,放在ModelAndView中
        mv.setViewName("hello");
        return mv;
    }
}

6.在WEB-INF目录下创建jsp目录,并创建hello.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


${msg}



7.配置Tomcat,将项目打包成jar包并测试

http://localhost:8080/hello

可能遇到的问题:404排查步骤:

1.查看控制台输出,看一下是不是少了jar包

2.看IDEA项目中是否存在lib依赖如没有请添加

你可能感兴趣的:(java,spring,maven)