SpringBoot复习:(28)【前后端不分离】自定义View

一、自定义View

package cn.edu.tju.view;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class MyView implements View {


    @Override
    public String getContentType() {
        return "text/html";
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.getWriter().write("hello, world.this is my view");

    }
}

二、控制器返回视图名称指向上述View

package cn.edu.tju.controller;

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

@Controller
public class ViewController {


    @RequestMapping("/view")
    public String getView(){
        return "myView";
    }
}


BeanNameViewResolver就会把我自定义的myView这个视图解析到MyVIew这个view类。