Spring MVC中重定向和视图呈现的区别 [英] Difference between redirect and view rendering in Spring MVC

查看:147
本文介绍了Spring MVC中重定向和视图呈现的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习Spring MVC知识时,有一些关于Spring返回类型的东西让我很困惑。

In learning about Spring MVC knowledge, there are some things about Spring return types that confuse me.

在本文档中:使用@RequestMapping映射请求,它们返回约会/新重定向: /约会

In this documentation: Mapping Requests With @RequestMapping they return appointments/newand redirect:/appointments.

代码

@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
    if (result.hasErrors()) {
        return "appointments/new";
    }
    appointmentBook.addAppointment(appointment);
    return "redirect:/appointments";
}

这两种回报类型之间的主要区别是什么?据我了解,第一种类型作为前进动作返回,但如果我是对的,为什么他们也发布 forward:/ 作为返回类型?

What's is the main difference between these two return types? As I understand it, the first type returns as a forward action, but if I'm right, why do they also publish forward:/ as a return type ?

推荐答案

第一个返回视图,而后一个重定向到另一个控制器请求映射操作。让我们来自代码本身。

First one returns the view while the later redirects to another controller request mapped action. Lets have alook from the code itself.

@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
    if (result.hasErrors()) {

这里当结果有错误时,它会呈现视图约会/新,以便用户可以输入正确的详细信息并再次添加应用程序。 在浏览器中不会更改网址

Here when the result have errors, it renders the view appointments/new so that the user can enter the correct details and add the apppointment again. URL will not change in the browser

        return "appointments/new";
    }
    appointmentBook.addAppointment(appointment);

但是在这里,当结果没有错误时,此控制器操作将网站重定向到URL /约会即可。检查网络浏览器更改为重定向网址的网址

But here, when the results has no error, this controller action redirect the website to the URL /appointments. Check the web browser URL which is changed to the redirected URL

    return "redirect:/appointments";
}

关于转发: vs 重定向:

引用此Satckoverflow答案为什么我们在Spring MVC中使用重定向

Quoted from this Satckoverflow answer Why do we use redirect in Spring MVC

使用控制器中的重定向前缀将生成一个HTTP响应,其中包含302状态代码和指向重定向URL的位置标头。然后,浏览器将重定向到该URL(第一个请求中显示的模型将丢失,浏览器URL将是第二个)。

使用正向前缀,转发将由servlet在内部完成,因此不需要第二个请求(URL将保持不变)。前缀前缀仅应用于浏览器可以安全重复的请求中。当您发送更改数据库状态的表单时,情况并非如此(重新加载浏览器将导致重复提交)。在这些情况下,您应该使用重定向并应用POST-redirect-GET模式。

Using the forward prefix, the forward will be done internally by the servlet, so there's no need of a second request (URL will remain the same). The forward prefix should only be used in requests that can be safely repeated by the browser. That's not the case when you send a form which changes the database state (reloading the browser will lead to duplicate submissions). In these cases you should use redirect and apply the POST-redirect-GET pattern.

这篇关于Spring MVC中重定向和视图呈现的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆