在Spring MVC中,你可以通过配置不同的RequestMapping来返回HTML或JSON。以下是一个简单的例子:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
@RequestMapping("/example")
public class ExampleController {
 
    @GetMapping("/html")
    public ModelAndView html() {
        ModelAndView modelAndView = new ModelAndView("example");
        modelAndView.addObject("message", "Hello, this is HTML");
        return modelAndView;
    }
 
    @GetMapping("/json")
    @ResponseBody
    public String json() {
        return "{\"message\": \"Hello, this is JSON\"}";
    }
}在上述代码中:
html()方法使用ModelAndView返回HTML模板,模板名通过构造函数传入,并可以添加模型数据。json()方法使用@ResponseBody注解,Spring MVC会自动将返回的字符串转换为JSON格式。
确保你的Spring MVC配置中有对应的HTML模板引擎(如Thymeleaf, Freemarker等),以及必要的配置来支持@ResponseBody注解,这样Spring MVC就可以正确处理并返回JSON响应。