Not able to get proper results using Apache Shiro configuration - java

I am trying to use apache shiro into my project as I have to create a role based mechanism into my project. I created a demo project with following configurations...
I created following files into my project -
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shiro Web Test</title>
</head>
<body>
<h1>This is a test for Shiro Web Framework</h1>
Click Here!
</body>
</html>
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shiro Web Test : Login Page</title>
</head>
<body>
<%! String errorMessage = null; %>
<%
errorMessage = (String) request.getAttribute("shiroLoginFailure");
if (errorMessage != null) { %>
<font color="red">Invalid Login: ${errorMessage}</font><br/>
<font color="black"><h3>Enter login information...</h3></font>
<% } else { %>
<font color="black"><h3>Enter login information...</h3></font>
<% } %>
<form action="loginTest.do" method="POST">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" placeholder="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="password" /></td>
</tr>
</table>
<input type="checkbox" value="true" name="rememberMe" />Remember Me?<br />
<input type="submit" value="Sign In" />
</form>
</body>
</html>
success.jsp
denied.jsp
logout.jsp
showUser.jsp
My shiro.ini configuration is as follows -
# =======================
# Shiro INI configuration
# =======================
[main]
authc = org.apache.shiro.web.filter.authc.FormAuthenticationFilter
roles = org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
authc.loginUrl = /login.jsp
authc.failureKeyAttribute = shiroLoginFailure
roles.unauthorizedUrl = /denied.jsp
[users]
admin = password, ROLE_ADMIN
member = password, ROLE_MEMBER
[roles]
ROLE_ADMIN = *
[urls]
/success.jsp = authc, roles[ROLE_MEMBER]
/secret.jsp = roles[ROLE_ADMIN]
I am using a servlet LoginTestServlet.java to dispatch to login.jsp page or success.jsp after authentication is successful/unsuccessful -
public class LoginTestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
generateResponse(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
generateResponse(request, response);
}
protected void generateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
UserCredentials user = new UserCredentials();
user.setUserName(request.getParameter("username"));
user.setPassword(request.getParameter("password"));
if (user.getUserName() != null && user.getPassword() != null) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
try {
currentUser.login(token);
Session session = currentUser.getSession();
session.setAttribute("user", user.getUserName());
} catch (UnknownAccountException uae) {
request.setAttribute("shiroLoginFailure", uae.getMessage());
System.err.println("Exception type: " + uae.getClass().getName());
System.err.println("Error due to: " + uae.getMessage());
} catch (IncorrectCredentialsException iae) {
request.setAttribute("shiroLoginFailure", iae.getMessage());
System.err.println("Exception type: " + iae.getClass().getName());
System.err.println("Error due to: " + iae.getMessage());
} catch (LockedAccountException lae) {
request.setAttribute("shiroLoginFailure", lae.getMessage());
System.err.println("Exception type: " + lae.getClass().getName());
System.err.println("Error due to: " + lae.getMessage());
} catch (AuthenticationException ae) {
request.setAttribute("shiroLoginFailure", ae.getMessage());
System.err.println("Exception type: " + ae.getClass().getName());
System.err.println("Error due to: " + ae.getMessage());
} catch (Exception e) {
request.setAttribute("shiroLoginFailure", e.getMessage());
System.err.println("Exception type: " + e.getClass().getName());
System.err.println("Error due to: " + e.getMessage());
}
RequestDispatcher view = null;
if (currentUser.isAuthenticated() && currentUser.hasRole("ROLE_MEMBER")) {
view = request.getRequestDispatcher("success.jsp");
view.forward(request, response);
} else if (currentUser.isAuthenticated() && currentUser.hasRole("ROLE_ADMIN")) {
view = request.getRequestDispatcher("secret.jsp");
view.forward(request, response);
} else {
view = request.getRequestDispatcher("login.jsp");
view.forward(request, response);
}
}
}//end of generateResponse()
}//end of class
I am using TOMCAT 6.0.
My problem is -
Whenever I am trying to enter credentials at login.jsp page, its automatically taking me to the respective page for the credentials I enter. Ex., if I try to enter ROLE_MEMBER credentials after clicking for success.jsp, its taking me to success.jsp page. But if I try to enter ROLE_ADMIN after clicking for same success.jsp, its automatically taking me to secret.jsp as per the servlet code written instead of going to denied.jsp.
How to make a generic code without writing a separate servlet for each resource to show login success or denied page?
Also, is there any way to create custom permissions in shiro for every resource? If yes, then how. If there is any link to this, I would be grateful to you.
Thanks all.

I'm wondering why you've decided to handle the authentication inside a servlet rather than using the pre-built filter as is already defined in the guide (among other things, you seem to be reloading the configuration and creating a new SecurityManager on every request...). The filter should handle the details in #1 for you.
If you insist on using a servlet, you need to add a value either to the session or as a parameter to the request to login.jsp which tells it where it should redirect the user after successful authentication and read that parameter once the user is authenticated.
Regarding #2, you are simply forwarding success.jsp after successful authentication. You aren't either 1) explicitly checking the user's roles or allowing the framework to do so for you. Again, switching to the filter should resolve this for you.

Related

java.lang.IllegalStateException: Cannot (forward | sendRedirect JSP/Java

I read some information about my issue here
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
but I didn't manage to solve my problem with it.
I've got a index.jsp page which should only be accessible to authorized users.
To do so, I use a java file which will feed the session with this information.
When I access my index, if the session is empty I go to my java part to check it, else I just display the content or not.
From my understanding, my issue is that I call this java part twice but I don't know where.
Could you please help me ?
Java code:
public class GroupeUtilisateur extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connBDUtil = null;
String autorise = "";
autorise = CheckAuth.isAllowed(request, response, "IML-Thanact-Admin;IML-Thanact-User");
HttpSession session = request.getSession();
/* Mise en session d'une chaîne de caractères */
session.setAttribute( "autorisation", autorise );
String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
And this is my index.jsp (minus non important parts)
<%# page language="java" import="java.util.*"%>
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<%# page session="true" %>
<head>
// In this script I initialise a datatable and some button will only be available for admin so I need to get the autorisation to
<script type='text/javascript' class='init'>
var authScript = '${sessionScope.autorisation}'; // Récupération de l'autorisation récupérée par GroupeUtilisateur.
</script>
</head>
<body>
<div class ="err"> <c:out value="${sessionScope.message}"/> </div>
<c:set var = "auth" scope = "session" value = "${sessionScope.autorisation}"/> <!-- Récupération de l autorisation pour la session -->
<!--
<div class ="err"> Log Autorisation : [<c:out value = "${auth}"/>] </div>
<div class ="err"> Log Autorisation sans var : [<c:out value = "${sessionScope.autorisation}"/>] </div>
-->
<c:choose>
<c:when test = "${empty auth}">
<div class ="err"> Empy session we go to the java part <c:out value="${sessionScope.autorisation}"/> </div>
<script language="javascript"> document.location.href="./GroupeUtilisateur/" </script>
</c:when>
<c:when test = "${!fn:contains(auth, 'Thanact-Admin') && !fn:contains(auth, 'Thanact-User')}">
<div class ="err">Vous n êtes pas habilité à utiliser cet écran. - [<c:out value = "${auth}" />]</div>
<br/>
<input type="button" name="back" value="Retour" onClick="parent.location='/Thanact/index.jsp'" class="buttonGrey">
</c:when>
<c:otherwise>
<!-- my data-->
</c:otherwise>
</c:choose>
</body>
</html>
Thanks a lot for your help !
EDIT:
Ok so after further investigation I think I located the issue, but still don't know how to fix it.
In fact to see if the user connected belong to the correct AD group we check the session. This is a method used in different app on our ecosystem, I didn't create it.
I think, it is the one who do this :
public class CheckAuth
{
//...
public static String isAllowed(
HttpServletRequest request,
HttpServletResponse response,
String groupMember,
String millPosition,
String forWhat) throws IOException, ServletException
{
//...
String auth = request.getHeader("Authorization");
if (auth == null)
{
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NTLM");
response.flushBuffer();
return "KO" ;
}
//...
}
}
It looks like after setting the header, the servlet is called again.
I need this bit because I can't get the username without.
How may I fix this ?

Logout servlet doesn't work: first last name and logout button are still visible after logout

I have a logout servlet that doesn't seem to work. After I go to /logout page it does redirect back to /home, however the user's first and last name as well as the Logout button are still present:
Before logout:
After logout:
LogoutServlet.java:
public class LogoutServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute("user");
session.invalidate();
}
response.sendRedirect(request.getContextPath() +
"/home");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
header.jsp:
<%# page import="comediansapp.entities.main.User" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div class = "header-container">
<div class = "header">
<%if(session.getAttribute("user") == null){%>
<div class = "header-buttons">
Login
Signup
</div>
<%
} else {%>
<div class="user-email">
<%
User user = (User) session.getAttribute("user");
out.println(user.getFirstname() + " " +
user.getLastname());
%>
</div>
<div class="button logout-button">
Logout
</div>
<%
}
%>
</div>
</div>
home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:include page="../shared/header.jsp" />
</body>
</html>
I forgot to put
#WebServlet("/logout")
on top of the LogoutServlet class.

A Login web using Java Servlet and mySQL, problems about connected to MySQL [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 6 years ago.
I wrote a login web and it can't work well. It may be some problem of MySQL connecting.
Here is the code. It's simple. There are ServletLogin.java and a index.jsp.
ServletLogin.java
package Login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
public class ServletLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String pass;
public ServletLogin() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String printout = "";
this.name = request.getParameter("username");
this.pass = request.getParameter("password");
if (name == "" || name == null || name.length() > 20) {
try {
printout = "20字以内ユーザネームを再入力ください";
request.setAttribute("message", printout);
response.sendRedirect("index.jsp");
return;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if (pass == "" || pass == null || pass.length() > 20) {
try {
printout = "20字以内のパスワードを再入力ください";
request.setAttribute("message", printout);
response.sendRedirect("index.jsp");
return;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
// database driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO: handle exception
System.out.println("Class not Found Exception");
}
// create url
String url = "jdbc:mysql://localhost:3306/databasedemo";
try {
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String sql = "select * from userinfo where username='"+name+"' and password= '"+pass+"'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ログイン</title>
<script type="text/javascript">
function changeImg()
{
document.getElementById("validateCodeImg").src="${pageContext.request.contextPath}/CheckCodeImage?" + Math.random();
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/ServletLogin">
<table border="0" align="center">
<tr height="30"></tr>
<tr align="center">
<td colspan="2"><font size="20">JAVA WEB</font></td>
</tr>
<tr height="30"></tr>
<tr height="50">
<td>ユーザネーム</td>
<td><input type="text" name="username" placeholder="ユーザネームを入力してください"></td>
</tr>
<tr height="50">
<td>パスワード</td>
<td><input type="password" name="password" placeholder="パスワードを入力してください"></td>
</tr>
<tr height="50">
<td><img alt="認めない" src="${pageContext.request.contextPath}/CheckCodeImage"
id="validateCodeImg" onclick="changeImg()">
</td>
<td><input type="text" name="checkcode" placeholder="右側の文字を入力してください"></td>
</tr>
<tr height="50">
<td colspan="2" align="center">
<input type="submit" name="login" value="ログイン">
</td>
</tr>
</table>
</form>
</body>
</html>
And here is my database called databasedemo.
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | Jack | 123456 |
| 2 | Mary | 654321 |
+--------+----------+----------+
I think I am stucked with command in ServletLogin.java. I was supposed to submit the form and it would turn to ServletLogin.java and do the command.
If the username and the password are null, recording to the code in Servlet.java, it will go back to index.jsp. And it went very well.
But if the username and the password are the same as it in my database, it should have to go to the page success.jsp. But when I run it, it shows nothing. Seems it has not been submitted and do the command in Servletlogin.java. and the Url shows http://localhost:8080/LoginDemo/ServletLogin?username=Jack&password=123456&checkcode=Axww&login=%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3
I'm so confused of it. I think I have problem about connecting to MySQL. But I don't know how to fix it. Please help me about it...
UPDATE
I have solved my problem!
When I run the code, the Exception shows Class not Found Exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/databasedemo. This is a exception of jdbc Driver.
When this exception shows, there's four reason:
Wrong URL. Please check the right code: Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/XX","root","XXXX"
Wrong Driver declaration, the right one is :com.mysql.jdbc.Driver
mysql-connector-java-5.1.40.jar must be the same version as your MySQL.
mysql-connector-java-5.1.40.jar has been put to the wrong position. The right position is to copy it in WEB-INF file.
As for me, I put .jar in the wrong position. And When I copy it in the file WEB-INF, my code run well. I hope this will help someone. And my code above is a simple webpage of login. I will continue to complete this java project.
And Thanks for everyone answered my question. #Ravi Kumar pointed out one of my mistakes, and I corrected it. It's a big mistake of me using MySQL.
My best guess is your query
select * from userinfo where username='"+name+"' and password= '"+pass+"'"
This basically select 1 | Jack | 123456
Now rs.getString(1)=1 ie id and rs.getString(2) is Jack ie. username
Instead use
rs.getString("username");
rs.getString("password");
You may also like to change your query to
select username,password from userinfo where username='"+name+"' and password= '"+pass+"'"
in order to make it work with existing code
There can be two possibilities as below:
1) You are seeing nothing in UI because there is nothing(no text content) in your success.jsp file.
You need to add some text as below in success.jsp page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
<p>Success!!!</p>
</body>
I guess you are not getting any exception in both UI and Server console.
2) You need to traverse through the resultSetObject in order to fetch correct username and password values.
So, replace your below code:
if (rs.next()) {
if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}
With ,
while(rs.next()){
if(this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

How can I Post parameter from JSP to HTTP using Java

I want to sent parameter from JSP to HTTP Servlet. but it doesn't work:(
I would like create a button to sent information to disable/enable user.
I'm still new to JSP and HTTP.
I hope can some one help me.
I hope it's enough to Overview
here my code:
admin.jsp
<%#page import="model.*"%>
<%#page import="java.util.*"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
List<Category> categories = (List<Category>) request.getAttribute("categories");
List<User> users = (List<User>) request.getAttribute("users");
User credentials = (User) request.getSession().getAttribute("credentials");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<jsp:include page="/WEB-INF/navbar.jsp"></jsp:include>
<h1 style="color:green;">Admin Control Page</h1>
<h2>categories</h2>
<% for (Category category : categories) { %>
<%=category.getName()%><br/>
<% } %>
<form method="post" action="<%=request.getContextPath()%>/admin" accept-charset="iso-8859-1">
<br/>
add new category: <input name="categoryName" />
<input type="hidden" name="event" value="createCategory" />
<input type="submit" />
</form>
<h2>users</h2>
<% for (User user : users){
if(user.getRole().getId()!= 1){
out.println("<a href='"+request.getContextPath()+"/user/"+user.getUsername()+"'><b>"+user.getUsername()+"</b></a>");
int id = user.getId();
%>
<%if(user.isEnabled()){ %>
//My Problem is here
<form action="/admin" method="POST">
<input value="<%user.getId();%>">
<input type="submit" value="Submit" />
</form>
<%}else if(!user.isEnabled()){
%>
// TODO Button
<%}%>
<p><hr>
<%
}
}
%>
</body>
</html>
AdminController.java
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DatabaseManager;
import model.Category;
import model.User;
#WebServlet("/admin/*")
public class AdminController extends HttpServlet {
private DatabaseManager db = DatabaseManager.getInstance();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// check admin, if not "error"
User user = (User) req.getSession().getAttribute("credentials");
if (user == null || !user.getRole().getName().equals("admin")) {
resp.sendError(403);
return;
}
// load page
req.setAttribute("categories", db.getCategoryDAO().findAll());
req.setAttribute("users", db.getUserDAO().findAll());
req.getRequestDispatcher("/WEB-INF/admin.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// event
String event = req.getParameter("event");
// create new category
if (event.equals("createCategory")) {
String categoryName = req.getParameter("categoryName").trim();
try {
Category cat = new Category();
cat.setName(categoryName);
db.getCategoryDAO().create(cat);
} catch (IllegalArgumentException e) {
// error
req.setAttribute("msg", e.getMessage());
doGet(req, resp);
return;
}
// Create successful
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
String idTemp = req.getParameter("id");
try{
int id = Integer.parseInt(idTemp);
User user = db.getUserDAO().findById(id);
user.setEnabled(false);
} catch(IllegalArgumentException e){
e.getMessage();
return;
}
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
}
Change
#WebServlet("/admin/*")
To
#WebServlet("/admin")
And you can use either:
action="<%=request.getContextPath()%>/admin" or action="admin".
And if you are still having error then mention the error name :)

Categories

Resources