spring mvc中的html页面跳转

配置视图解析器

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

一、使用controller(常规用法)

    @Controller
    public class testController{
		@RequestMapping(value = "/hello.jsp")
		public String goHello(){
			return "hello";
		}
	}

返回的字符串会转换为ModelAndView对象,然后经过视图解析器的处理找到对应的视图并进行渲染。
在使用过程中发现了另一种情况,返回值为void,也能跳转到对应的页面,使用的是springboot框架,不知道是不是框架的关系。

    @Controller
    public class testController{
    	@RequestMapping(value = "/hello.html")
    	public void goHello(){
    	}
    }

二、使用配置项的方法

1.使用java的方式添加配置项
继承WebMvcConfigurer接口,重写addViewControllers(ViewControllerRegistry registry)方法

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("home");
        }
    }

当直接在浏览器中访问http://localhost:8080/时,会跳转到home.jsp页面

2.在配置文件中添加配置项


这种方法效果同上java方法

你可能感兴趣的:(Spring)