java - 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>
解决方案
从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";
延伸阅读
推荐阅读
- django - 物化模型select2搜索输入中的django-autocompelete-light不起作用
- azure - 获取 Azure AD B2C 策略的 SAML 元数据时出错 - AADB2C90022
- react-native - 如何使用 appium 在 react-native 项目中编辑文件
- ios - Firebase 查询结果 SWIFT 的奇怪行为
- java - RxJava2 成功总是调用两次
- spring - Spring Cache 处理 Cache-Control=no-cache
- ios - iOS 通用链接(在调试时)不起作用?
- css - 创建一个使用 100% 弹性表的“行高”的行尾“单元格”,而不考虑其他项目的弹性包装
- delphi - Delphi TEdit onClick - 启用并执行其他操作
- go - 如何在 GoLand 中运行并将命令行参数传递给 main.go?