【发布时间】:2020-06-25 17:38:10
【问题描述】:
我有一个需要参数名称的方法,我将其设置为会话属性,因为它将在整个会话中得到修复。但是,我无法将其添加到函数中。任何帮助表示赞赏。
设置会话属性的LoginController类
@Controller
@SessionAttributes({"name", "date"})
public class LoginController {
@Autowired
LoginService service;
/*
* 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!";
}
@RequestMapping(value ="/")
public String returnLogin() {
return "redirect:/loginPage";
}
// 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 to be used for user input
// 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) {
if (service.validateUser(name, password)) {
// Send name to .jsp
// use addAttrible( nameAtJSP, nameInRequestParam ) to check for null
model.addAttribute("name", name);
model.addAttribute("passWelcome", password);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date());
model.addAttribute("date", date);
}
else {
model.put("errorMessage","Invalid credentials");
return loginPage();
}
return "welcome";
}
我的控制器类。我已经注释了我需要添加会话属性的部分。
@Controller
public class ToDoController {
@Autowired
private ToDoService service;
@RequestMapping(value = "/list-todo", method= RequestMethod.GET)
public String showToDo(ModelMap model, String name, String date) {
model.addAttribute("toDos", service.retrieveTodos("in28Minutes"));
model.addAttribute("name", name);
model.addAttribute("date", date);
// Only returns to the jsp
return "list-todos";
}
@RequestMapping(value = "/add-todo", method= RequestMethod.GET)
public String addToDo() {
return "addToDo";
}
@RequestMapping(value = "/add-todo", method= RequestMethod.POST)
public String addToDo(ModelMap model,@RequestParam String description) {
// SESSION ATTRIBUTE NAME
model.addAttribute("name");
service.addTodo((String) model.get("name"), description, new Date(), false);
model.clear();
return "redirect:/list-todo";
}
【问题讨论】:
-
设置为
HttpSession? -
@pirho 你能用代码详细说明吗/
-
你:“我把它设置为会话属性”,你是怎么设置的?
-
@pirho 添加了信息
标签: java spring spring-mvc session controller