首页 > 解决方案 > Spring MVC 从控制器获取日期到 JSP

问题描述

所以我有一个简单的登录页面,登录后,我想在登录成功后在页面中显示日期。我可以在 JSP 中使用 scriptlet,但我知道这是不好的做法,所以我想找到一种替代方法。我相信使用控制器,设置一个返回 JSP 文件的方法将是最好的方法,但我不完全确定如何实现它。任何帮助表示赞赏!

我的控制器类

public class LoginController {

/*
 *  Map /login to this method 
 *  localhost:8080/spring-mvc/login
 *  spring-mvc -> dispatcher (todo-servlet.xml)
 *  dispatcher detects login url
 *  dispatcher use view resolver to find .jsp file based on String. In this case, login
 *  view resolver locates login.jsp and shows the content to user via http
 */
@RequestMapping(value = "/test")
// Mark this method as an actual repsonse back to user
@ResponseBody
public String test() {
    return "Hello, world!";
}

// Only handles get request from the login page
@RequestMapping(value = "/login", method= RequestMethod.GET)
public String loginPage() { 
    // search through the view resolver for login.jsp
    return "login";
}

// Only handles post request from the login page
@RequestMapping(value = "/login", method= RequestMethod.POST)
// @RequestParm grabs query param, it has to have the same name as it states in the jsp
// Model is used to supply attributes to views
// ModelMap has the same functionality has model except it has an addition function where it allows a collection of attributes
public String handleLogin(@RequestParam String name, @RequestParam String password, ModelMap model) {
    // Send name to .jsp 
    // use addAttrible( nameAtJSP, nameInRequestParam ) to check for null
    model.addAttribute("name", name);
    model.addAttribute("passWelcome", password);
    return "welcome";   
}

/*
 * @RequestMapping(value = "/login", method= RequestMethod.POST) public String
 * getDate(@RequestParam String date, ModelMap model) { SimpleDateFormat sdf =
 * new SimpleDateFormat("dd/MM/yyyy"); date = sdf.format(new Date());
 * model.addAttribute("date", date); return "welcome"; }
 */

我的welcome.jsp 成功登录后显示信息

<html>
  <head>
   <!-- To add value to param url localhost:8080/?name=alex -->

   <title>Welcome page</title>
  </head>
  <body>
    <%-- ${String} picks up param  --%>
    <div>Current date is ${date}</div>
    Welcome ${name} and your password is ${passWelcome}
  </body>
</html>

标签: javaspringspring-mvcjspcontroller

解决方案


POST处理程序,重定向到GET处理程序。从该处理程序返回您的welcome视图。GET

创建另一个处理程序(可能在单独的控制器中,例如HomeController):

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String showHome(ModelMap model) {
    model.put("date", new Date());
    // other attributes

    return "welcome";
}

"/login" POST处理程序中:

return "redirect:/home";

延伸阅读


推荐阅读