SpringMVC使用重定向后,如何去掉url后面的地址?

SpringMVC登录与重定向
本文介绍了一个基于SpringMVC的用户登录实现方法,详细解释了如何通过POST请求进行用户验证,并在登录成功后使用重定向跳转到首页。同时,文章提供了去除重定向后URL参数的方法,即在springmvc.xml中添加配置来忽略默认模型。
//用户登录
    @RequestMapping(value="/goLogin",method= RequestMethod.POST)
    public String goLogin(User user, Map<Object, Object> map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("登录1");
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
		//按用户名密码查询
        List<User> listUser = userService.getUser(user);
        if (!listUser.toString().equals("[]")) {
            System.out.println("登录2");
            String username = listUser.get(0).getUsername();
            String password = listUser.get(0).getPassword();
            map.put("username", username);
            map.put("password", password);
            System.out.println("登录成功");
            return "redirect:index";// 重定向
        } else {
            return "error";
        }
    }
@RequestMapping(value = "index")
    public String index(){
        return "index";
    }

使用重定向后,index方法是不能设置method= RequestMethod.POST。

导致url后面会带一系列的参数。

如何去掉?

解决办法:

在springmvc.xml上添加如下配置:

    <mvc:annotation-driven ignore-default-model-on-redirect="true" />

就OK啦!

敲代码最幸福的事,是当天出现的问题当天解决!欧耶!

### 实现Spring MVC POST 请求重定向 在Spring MVC框架中,实现POST请求后的重定向操作是一个常见的需求。当接收到`POST`请求并完成相应的业务逻辑处理之后,通常会希望将用户重定向到另一个页面或资源上。 对于带有路径变量的情况,可以在控制器方法内定义@RequestMapping注解来指定HTTP请求的方法类型以及URL模式,并利用字符串形式的视图名称作为返回值来进行重定向。例如: ```java @RequestMapping(value = "/files/{path}", method = RequestMethod.POST) public String upload(@PathVariable("path") String path, ...) { // 执行上传文件或其他业务逻辑... return "redirect:/view/files/" + path; // 或者更简洁的方式:"redirect:files/{path}"[^2] } ``` 这里需要注意的是,在执行重定向的过程中,如果想要保留某些数据供目标地址使用,则可以借助于`RedirectAttributes`对象传递临时性的属性给下一个请求。这有助于保持用户体验的一致性和连贯性而不必担心GET请求可能带来的重复提交问题。 另外一种情况是关于如何确保模型(Model)中的数据能够在重定向后仍然可用。由于默认情况下,原始请求的数据不会被自动携带至新的请求中,因此需要显式地向`RedirectAttributes`添加这些信息以便它们能在后续请求中访问得到[^3]。 ```java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.support.RedirectAttributes; // ... @RequestMapping(method = RequestMethod.POST) public String handleFormSubmission(RedirectAttributes redirectAttrs){ // 处理表单... // 将消息添加到flash属性中 redirectAttrs.addFlashAttribute("message", "成功保存!"); return "redirect:/success"; } ``` 上述代码片段展示了如何通过`addFlashAttribute()`方法把特定的信息存储起来用于下一次请求显示出来。这种方式非常适合用来反馈操作结果或是其他短暂存在的状态提示。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值