我有一个登录表单,成功后将重定向到servlet。我正在使用apache shiro进行身份验证,并且尝试提取表单提交的用户名,以便可以在servlet中使用它。我想知道shiro是否已将这些值存储在会话中。如果是这样,如何提取它们,以便可以在servlet中使用它们?我尝试过在表单上执行表单操作,并request.getParameter("username")
在Servlet中使用提取用户名,但在使用shiro时似乎不起作用。我已经阅读了Shiro文档并也阅读了类似的问题。我仍然不确定在哪里实际配置和提取会话变量。是shiro.ini
在我的servlet中还是在我的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 Tag库
或者
调用request.getUserPrincipal().getName()
时应返回主题的用户名。
或者
你也可以从调用中获得所需的信息Subject.getPrincpal()
,尽管这取决于你领域的实现。