美文网首页
关于java web项目中绝对路径与相对路径问题

关于java web项目中绝对路径与相对路径问题

作者: camlboy | 来源:发表于2017-04-25 18:05 被阅读699次
@Controller
@RequestMapping("/app")
public class MainController {


@RequestMapping(value = "/loginAction", method = RequestMethod.POST)
    private String loginAction(@Valid @ModelAttribute("user") User user , BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "login";
        }

        Date current_date = new Date();
        SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        user.setCreateTime(SimpleDateFormat.format(current_date.getTime()));
        user.setStatus("enable");

        int statue = userService.login(user);
        if(statue > 0){
            return "redirect:forMain";
        }else {
            return "login";
        }

    }

@RequestMapping(value = "/forMain", method = RequestMethod.GET)
    private String froMain(){
        return "index";
    }
}

为了防止表单重复提交,我这边在用户注册以后重定向到主界面,如果返回路径写为:return "redirect:/forMain";假设我们的项目部署在本地localhost:8080;此时mvc会视为绝对路径,将跳转到http://localhost:8080/forMain,此时发现404了,实质上我们应该使用相对路径,因为我们的login请求和forMain请求在同一个controller下,所以改为``return "redirect:forMain";此时会跳转到http://localhost:8080/app/forMain`.

还有一种就是在Jsp中的请求,此时我可能在hello.jsp中要链接到另外一个路径下,如下所示:
<a href="${pageContext.request.contextPath}/user/imgInfo">进入用户图片上传界面</a>
我们这里有另外一个UserController:

@Controller
@RequestMapping("/user")
public class UserController {

    // 处理上传的
    @RequestMapping("/imgInfo")
    public String upload2() {
        return "user/fileupload";
    }
}

由于我们的hello.jsp请求路径为http://localhost:8080/app/hello,若我们写为<a href="${pageContext.request.contextPath}user/imgInfo">进入用户图片上传界面</a>,则跳转路径为http://localhost:8080/app/user/imgInfo.所以这里要使用绝对路径。

相关文章

网友评论

      本文标题:关于java web项目中绝对路径与相对路径问题

      本文链接:https://www.haomeiwen.com/subject/xpavzttx.html