You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC中如何携带对象跳转至另一页面并展示

Hey there! Let's break down how to carry an object to another page and display it in your Spring MVC setup. Here are a few practical approaches tailored to your current code:


方案1:ModelAndView + 服务器端模板渲染(适合传统MVC场景)

If your song.html is a server-side template (like Thymeleaf or JSP), you can adjust your controller to pass the object into the model and redirect directly to the view.

First, change @RestController to @Controller (since @RestController returns JSON instead of triggering a page redirect):

@Controller
@RequestMapping("/songs")
public class SongController {

    @RequestMapping("/getSong")
    public ModelAndView getSong(String id) {
        System.out.println("Song id " + id);
        Optional<Track> trackOpt = trackService.findById(id); // Replace with your actual service call
        ModelAndView mav = new ModelAndView("/song.html");
        
        if (trackOpt.isPresent()) {
            mav.addObject("track", trackOpt.get()); // Attach the object to the model
        }
        return mav;
    }
}

Then, in your song.html (using Thymeleaf as an example), display the object:

<div th:if="${track}">
    <h2>Song Details</h2>
    <p>ID: <span th:text="${track.id}"></span></p>
    <p>Title: <span th:text="${track.title}"></span></p>
    <!-- Add other track properties as needed -->
</div>

方案2:Flash Attributes(适合重定向场景,避免 duplicate submissions)

If you need to redirect to the /songs page (your pre-configured ViewController) and carry the object without exposing it in the URL, use Flash Attributes. These store data in the session temporarily and clear it after the redirect.

Modify your controller like this:

@Controller
@RequestMapping("/songs")
public class SongController {

    @RequestMapping("/getSong")
    public String getSong(String id, RedirectAttributes redirectAttributes) {
        System.out.println("Song id " + id);
        Optional<Track> trackOpt = trackService.findById(id);
        
        if (trackOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("track", trackOpt.get());
        }
        return "redirect:/songs"; // Redirect to your ViewController path
    }
}

You can then access the ${track} object in song.html the same way as in the first approach.


方案3:Frontend-First Approach(适合前后端分离)

If your index.html and song.html are static pages (no server-side templating), use JavaScript to fetch the object, store it temporarily, then redirect and render it.

First, keep your @RestController to return JSON:

@RestController
@RequestMapping("/songs")
public class SongController {

    @RequestMapping("/getSong")
    public ResponseEntity<Track> getSong(String id) {
        System.out.println("Song id " + id);
        Optional<Track> trackOpt = trackService.findById(id);
        
        return trackOpt.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}

Then, add this logic to your index.html to handle the jump:

// Trigger this function when the user clicks to view a song
function navigateToSongPage(id) {
    fetch(`/songs/getSong?id=${id}`)
        .then(res => res.json())
        .then(track => {
            // Store the object in localStorage temporarily
            localStorage.setItem("currentTrack", JSON.stringify(track));
            // Redirect to the song page
            window.location.href = "/songs";
        })
        .catch(err => console.error("Failed to fetch song:", err));
}

Finally, render the object in song.html:

window.onload = function() {
    const trackData = localStorage.getItem("currentTrack");
    if (trackData) {
        const track = JSON.parse(trackData);
        // Populate the page with track data
        document.getElementById("song-id").textContent = track.id;
        document.getElementById("song-title").textContent = track.title;
        
        // Clean up the storage after use
        localStorage.removeItem("currentTrack");
    }
}

Corresponding HTML in song.html:

<div id="song-details">
    <p>ID: <span id="song-id"></span></p>
    <p>Title: <span id="song-title"></span></p>
</div>

方案4:URL Parameters(仅适合 simple objects)

If your Track object has only a few simple properties, you can pass them directly in the URL.

In your frontend, build the URL and redirect:

function goToSongPage(track) {
    const encodedTitle = encodeURIComponent(track.title);
    window.location.href = `/songs?trackId=${track.id}&trackTitle=${encodedTitle}`;
}

Then, in song.html, read the parameters and render:

function getUrlParam(paramName) {
    const params = new URLSearchParams(window.location.search);
    return params.get(paramName);
}

window.onload = function() {
    const trackId = getUrlParam("trackId");
    const trackTitle = getUrlParam("trackTitle");
    
    if (trackId) {
        document.getElementById("song-id").textContent = trackId;
        document.getElementById("song-title").textContent = trackTitle;
    }
}

Quick Notes:

  • For server-side templating, make sure your view resolver is configured correctly to locate song.html.
  • Flash attributes require Spring Session support (enabled by default in most setups).
  • Avoid storing sensitive data in localStorage for frontend approaches.

内容的提问来源于stack exchange,提问作者Chocologocal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:26:17