我正在尝试在用户登录时将用户名设置为Http会话属性,但它会给我一个错误
必需的字符串参数'username'不存在
这是我的控制器类getLoginForm方法。在这里,我试图从输入中获取用户名字符串并将其放入httpSession(因为我需要在其他请求中使用此用户名)。
package com.vandh.app.controller;
import javax.servlet.http.HttpSession;
@Controller
@SessionAttributes("username")
public class LoginController {
@RequestMapping(value = { "/", "/home" })
public String getUserDefault() {
return "home";
}
@RequestMapping("/login")
public ModelAndView getLoginForm(@ModelAttribute Users users,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
@RequestParam(value="username") String username,
HttpSession httpSession) {
String message = "";
if (error != null) {
message = "Incorrect username or password !";
} else if (logout != null) {
message = "Logout successful !";
}
else
if(error==null)
{
httpSession.setAttribute("username", username);
}
return new ModelAndView("login", "message", message);
}
@RequestMapping("/admin**")
public String getAdminProfile() {
return "admin";
}
@RequestMapping("/403")
public ModelAndView getAccessDenied() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
String username = "";
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
username = userDetail.getUsername();
}
return new ModelAndView("403", "username", username);
}
}
这是我在DB(MySQL)中查找用户的DAO类
@Repository("loginDao")
public class LoginDaoImpl implements LoginDao {
@Autowired
SessionFactory sessionFactory;
//public String userLogIn; // checking username in auth. process
Session session = null;
Transaction tx = null;
@Override
public Users findByUserName(String username ) {
String login = username;
session = sessionFactory.openSession();
tx = session.getTransaction();
session.beginTransaction();
Users user = (Users) session.load(Users.class, new String(username));
tx.commit();
return user;
}
}
这是我的login.jsp页面
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login </title>
</head>
<body>
<br /> <br /> <br />
<div style="border: 1px solid black; width: 300px; padding-top: 10px;">
<br /> Please enter your username and password to login ! <br /> <span
style="color: red">${message}</span> <br />
<form:form method="post" action="j_spring_security_check"
modelAttribute="users">
<table>
<tr>
<td>Username:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>