如何从apacheshiro登录表单中提取会话值



我有一个登录表单,成功后会重定向到servlet。我正在使用apacheshiro进行身份验证,并试图提取表单提交的用户名,以便在servlet中使用它。我想知道shiro是否已经在会话中存储了这些值。如果是这样,我如何提取这些内容以便在servlet中使用它们?我曾尝试在表单上执行表单操作,并在servlet中使用request.getParameter("username")提取用户名,但在使用shiro时似乎不起作用。我读过shiro的文档,也读过类似的问题。我仍然不确定在哪里实际配置和提取会话变量。它是在shiro.ini中还是在我的servlet中?

shiro.ini

jdbcRealm= org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.authenticationQuery = SELECT password from user where username = ?
jdbcRealm.userRolesQuery = SELECT role from userroles where userID = (select id FROM user WHERE username = ?)
;jdbcRealm.permissionsQuery  = ??????
ds = com.mysql.cj.jdbc.MysqlDataSource
ds.serverName = localhost
ds.user = root
;ds.password = shiro
ds.databaseName = shiro
jdbcRealm.dataSource= $ds
passwordMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName = SHA-256
credentialsMatcher.storedCredentialsHexEncoded = true
credentialsMatcher.hashIterations = 5000
authc.loginUrl = /login.jsp
authc.usernameParam = username
authc.passwordParam = password
;authc.rememberMeParam = rememberMe
authc.successUrl = /secret/SecretStockServlet
logout.redirectUrl = /login.jsp
[urls]
/login.jsp = authc 
/secret/** = authc 
/logout = logout

登录表单

<form name="loginform" id ="loginform" method="post">
<div class="container">
<h1>Log in</h1>
<p>Please fill in this form to log in.</p>
<hr>
<label for="username"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="username" id="username" required>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<hr>
<button type="submit" class="loginbtn">Log in</button>
</div>
<div class="container signin">
<p>Need to register? <a href="register.jsp">Sign up</a>.</p>
</div>
</form>

/secret/SecretStockServlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String address;
try {
List<SalesStock> list = stockRepository.getAllSalesStock();
address = "/secret/stock.jsp";
Subject currentUser = SecurityUtils.getSubject();
Session session = (Session) currentUser.getSession();
request.setAttribute("list", list);
} catch (Exception ex) {
address = "/error.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}

如果您使用JSP,您可以使用Shiro标记库

调用request.getUserPrincipal().getName()应返回受试者的用户名。

您也可以通过调用Subject.getPrincpal()获得所需的信息,尽管这取决于您的领域的实现。

最新更新