java - Bean 从 Controller 到另一个 Controller

标签 java spring-mvc

如何将 Bean 从一个 Controller 传递到另一个 Controller ?我尝试的是:

页面默认获取 Controller

@RequestMapping( value = "/{prePath:[a-zA-Z]+}/module", method = RequestMethod.GET )
public String module( @RequestParam( defaultValue = "" )
String message, @RequestParam( defaultValue = "" )
String messageType, HttpServletRequest request, ModelMap model )
{
     model.addAttribute( "message", message );
     model.addAttribute( "messageType", messageType );
     return "als-student/module";
}

链接到 Controller

<a href="../${ usertype }/module/${ file_id }.do" >Spring Tutorial</a>

另一个 Controller 仅从数据库获取数据并假设将数据发送到另一个 Controller

@RequestMapping( value = "/{prePath:[a-zA-Z]+}/module/{file_id}" )
public String getModule( @PathVariable( "file_id" )
int fileId, Model model )
{
    try
    {
        FileBean fileBean = new FileDAO().getFileInfo( fileId );
        if( fileBean != null )
        {
            model.addAttribute( "fileBean", fileBean );
            return "redirect:../module.do";
        }
    }
    catch( Exception e )
    {
         e.printStackTrace();
    }

    return "redirect:../module.do?error";
}

但是我无法访问jsp,它什么也没显示。这是我访问它的方式

<p> ${ fileBean.fileName } </p>

最佳答案

您需要使用RedirectAttributes来实现此目的:

@RequestMapping( value = "/{prePath:[a-zA-Z]+}/module/{file_id}" )
public String getModule( @PathVariable( "file_id" )
int fileId, Model model, RedirectAttributes redirectAttributes)
{
    try
    {
        FileBean fileBean = new FileDAO().getFileInfo( fileId );
        if( fileBean != null )
        {
            //model.addAttribute( "fileBean", fileBean );
            redirectAttributes.addFlashAttribute("fileBean", fileBean);
            return "redirect:../module.do";
        }
    }
    catch( Exception e )
    {
         e.printStackTrace();
    }

    return "redirect:../module.do?error";
}

Flash 属性在重定向之前临时保存(通常在 session 中),以便在重定向之后可供请求使用并立即删除。

关于java - Bean 从 Controller 到另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662460/

相关文章:

java - 检测 TCP 连接重置的方法

java - 我怎么知道java库路径?

java.lang.ClassNotFoundException : org. hibernate.collection.internal.PersistentBag - 找不到我正在寻找的类

java - Spring MVC Maven 项目中的 org.springframework.beans.factory.BeanCreationException

java - 具有当前 elasticsearch 版本的 Spring Boot 应用程序

java数据库连接: jdbc

java的executeUpdate无法正常工作

java - 如何将大量值传递到 GET 请求参数中

spring - 将@RequestParam 绑定(bind)到对象而不是简单类型的简洁方法

Java Activity 变量