I created a signIn servlet:
#WebServlet(
name = "SignInServlet",
description = "check email & pass",
urlPatterns = {"/authorization_signin"}
)
public class SignInServlet extends javax.servlet.http.HttpServlet {
public SignInServlet(){
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws javax.servlet.ServletException, IOException {
request.setCharacterEncoding("UTF-8");
UserDataSet user = new UserDataSet();
SignInModel modelSignIn = new SignInModel();
user.setEmail(request.getParameter("email"));
user.setPassword(request.getParameter("password"));
user = modelSignIn.doSignIn(user);
if (request.getSession().getAttribute("loggedUser") == null) {
if (user != null) {
request.getSession().setAttribute("loggedUser", user); request.getRequestDispatcher("authorization.jsp").forward(request, response);
response.setStatus(HttpServletResponse.SC_OK);
} else {
request.setAttribute("errorMessage", "Email or password is incorrect");
request.getRequestDispatcher("index.jsp").forward(request, response);
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
When user is signed in, servlet redirects him to "authorization.jsp"
<body>
<%
if (request.getSession().getAttribute("loggedUser") != null){
UserDataSet user = (UserDataSet) request.getSession().getAttribute("loggedUser");
System.out.println("In author :" + request.getSession().getAttribute("loggedUser"));
%>
<h1> Hello <%= user.getFirstName() %> <%= user.getLastName() %>!</h1>
<h2>AUTORIZED!</h2>
Log Out
<%
}
else {
%>
<h1>GO HOME</h1>
<%
}
%>
</body>
Then browser shows this page and data for signed in user
If write into URL "localhost:8080" and go to "index.jsp", then
again on "authorization.jsp"
Filter check session:
#WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) req;
HttpServletResponse httpResponse = (HttpServletResponse) resp;
System.out.println("Enter filter");
System.out.println("Filter session: " + httpRequest.getSession(false).getAttribute("loggedUser"));
UserDataSet user = (UserDataSet) httpRequest.getSession(false).getAttribute("loggedUser");
if (user != null) {
System.out.println("CHAIN");
chain.doFilter(req, resp);
} else {
httpResponse.sendRedirect("/");
System.out.println("Not signin");
}
}
public void init(FilterConfig config) throws ServletException {
}
}
And getSession().getAttribute("loggedUser") returns null
Why?
Next text:
If I signed in and servlet open "authorization.jsp", then try to go throw URL on any *.jsp where session will be checked and the result will be null
What's wrong?
My friend had help me found answer for this question in some answers on stackoverflow
If you put something in the session with request.getSession().setAttribute you have to read it from the session, not the request. Try <%= session.getAttribute("test") %>
Link to answer
I used
<%= request.getParameter("loggedUser") %>
For some reason I saw [1] in java logs when I used request.getSession().getAttribute("loggedUser") , I also observed in the same code that request.getParameter works, at least when values are passed by query strings and the "unchecked or unsafe operations" disappears from the log .
So seems to me that can be a solution for this question.
[1]
_index__jsp.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Related
I have created two servlet page 1st-servlet page is RegistrationServlet and 2nd- servlet page is LoginServlet, and made an object for linked list so as to call it from other servlet but I am not able to call that object.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String name,email,pass;
name=request.getParameter("un");
email = request.getParameter("em");
pass = request.getParameter("pass");
LinkedList<String> a1=new LinkedList();
a1.add(name);
a1.add(pass);
if (!name.isEmpty() && !email.isEmpty() && !pass.isEmpty()) {
RequestDispatcher rd=getServletContext().getRequestDispatcher("/Login.html");
rd.forward(request, response);
request.getSession().setAttribute("someone", a1);
request.getRequestDispatcher("LoginServlet").forward(request, response);
} else {
RequestDispatcher rd1 = getServletContext().getRequestDispatcher("/Register.html");
rd1.include(request, response);
}
}
Other Servlet---------------------------------------
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String email = request.getParameter("eml");
String pass = request.getParameter("pass");
object fg;
fg = request.getSession().getAttribute("someone");
if(email.equals(fg.a1.get(0)) && pass.equals(fg.a1.get(1)))
{
System.out.println("sucess");
}
else{
System.out.println("not");
}
}
You put list into session by this command: request.getSession().setAttribute("someone", a1);
'a1' is a name of variable and is not put into session.
Value given by request.getSession().getAttribute("someone") must by of type List. This object does not have field 'a1'. So to get item of that list you have to write fg.get(0), not fg.a1.get(0).
I have project maven web-application. I have a few JSP files with HTML code and JSP tags. I have a connection in the local database and a few servlets.
Problem is that when I logged in to the app, I want to print a welcome message for the logged user.
This is the tag which should display a welcome message:
<div class="hello-text"><h1>Hello <span>${sessionScope.user_name}</span>. This is yours stats:</h1></div>
When I logged in the only text that I have is "Hello ${sessionScope.user_name}. This is your stats:
This is my servlet code for logging in:
#WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
private static final long serialVersionUID = 2717450811223035557L;
private UserRepository userRepository = new UserRepositoryBean();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String login = req.getParameter("login");
String password = req.getParameter("password");
PrintWriter writer = resp.getWriter();
if (login == null | login.isEmpty() | password == null | password.isEmpty()) {
writer.write("ERROR");
return;
} else {
if (userRepository.validateUser(login, password)) {
HttpSession session = req.getSession();
session.setAttribute("user_name", login);
resp.sendRedirect("profile.jsp");
} else {
req.setAttribute("error", "Invalid login or password. Try again.");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
writer.close();
}
}
Why I don't have a message, for example, Hello Admin. This is your stats:?
I always have Hello ${sessionScope.user_name}. This is your stats:...
A sendRedirect should not be mixed by other output of some page.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String login = req.getParameter("login");
String password = req.getParameter("password");
if (login.isEmpty() || password.isEmpty()) {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write("ERROR");
return;
}
if (userRepository.validateUser(login, password)) {
HttpSession session = req.getSession();
session.setAttribute("user_name", login);
resp.sendRedirect("profile.jsp");
} else {
req.setAttribute("error", "Invalid login or password. Try again.");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
The first if could be done by the validation - as empty input happens often - by a nice error message reposted to the same form with already done input saved.
If the JSP comes as HTML, then ensure it has a valid servlet mapping.
Also the JSP better should not be placed in a public directory, but maybe under WEB-INF/jsps/ or such.
<%
if(session == null) {
System.out.println("Expire");
response.sendRedirect("/login.jsp");
}else{
System.out.println("Not Expire");
}
%>
<%
HttpSession sess = request.getSession(false);
String email = sess.getAttribute("email").toString();
Connection conn = Database.getConnection();
Statement st = conn.createStatement();
String sql = "select * from login where email = '" + email + "' ";
ResultSet rs = st.executeQuery(sql);
%>
I tried to redirect the login.jsp page when session is expired.
But I am geeting error in "String email = sesss.getAttribute("email").toString();".
So anyone please help me to solve this error.
Basically I want to redirect to login.jsp page when the session is expired.
First of all. You are mixing JSP and Java code. You should separate it.
Keep Java code in controllers.
You can use:
if(request.getSession(false) == null) {
response.sendRedirect("/login.jsp");
}
"...If create is false and the request has no valid HttpSession, this method returns null."
For example create Authentication Filter
#WebServlet(
name = "AuthenticationFilter",
description = "Authentication Filter",
urlPatterns = "/AuthenticationFilter"
)
#WebFilter("*.jsp")
public class AuthenticationFilter implements Filter {
private ServletContext context;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.context = filterConfig.getServletContext();
this.context.log("AuthenticationFilter initialized");
}
#Override
public void destroy() {
//close any resources here
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
this.context.log("Requested Resource::" + uri);
HttpSession session = req.getSession(false);
Object user_o = req.getSession().getAttribute("username");
this.context.log("Authentication Filter, user_name::" + user_o);
if (user_o == null && !(uri.endsWith("index.jsp") || uri.endsWith("LoginUser"))) {
this.context.log("None authenticatied request, session:: " + session);
res.sendRedirect("index.jsp");
} else {
this.context.log("Authenticatied request, session:: " + session);
chain.doFilter(request, response);
}
}
I tried this and its working fine for me.
<%
if(session.getAttribute("email") == null) {
response.sendRedirect("login.jsp");
return ;
}
%>
I just put return statement and It will redirect to "login.jsp" when the session is expired.
I've a filter used for the login. It performs a textual checking, on fields "Username" and "Password". If and only if the textual checking is correctly done the request goes to the Servlet. This latter performs the control that has to interact with the Database. Is this chain correct?
Preface: I gather you're using homegrown login instead of container managed login. For all ways, see How to handle authentication/authorization with users in a database?
The filter (the interceptor) shouldn't check the validity of the username/password combo. That's the responsibility of the servlet (the controller).
The filter should merely check if the user is logged-in or not (usually by just checking the presence of a session attribute) and then continue the request or block it by redirecting back to the login page.
#WebFilter("/*")
public class LoginFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + "/login";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
// ...
}
The servlet should collect the submitted data, find the associated User in database and if found then store it as a session attribute and then redirect to the home page, else redisplay the form with validation errors.
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
#EJB
private UserService userService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Map<String, String> messages = new HashMap<String, String>();
if (username == null || username.isEmpty()) {
messages.put("username", "Please enter username");
}
if (password == null || password.isEmpty()) {
messages.put("password", "Please enter password");
}
if (messages.isEmpty()) {
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/home");
return;
} else {
messages.put("login", "Unknown login, please try again");
}
}
request.setAttribute("messages", messages);
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
See also:
Our servlet-filters wiki page
Our servlets wiki page
I am trying to get my first servlets to work. I have found some similar problems and solutions to them, but it´s not excatly what I would like to do.
This is my login servlet:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
if(LoginValidator.validate(username, password)){
HttpSession session = request.getSession();
session.setAttribute("user", username);
session.setMaxInactiveInterval(30*60);
Cookie sessionCookie = new Cookie("sessionKuki", username);
sessionCookie.setMaxAge(30*60);
response.addCookie(sessionCookie);
RequestDispatcher rd=request.getRequestDispatcher("paste.jsp"); //INSTEAD of paste.jsp I would like to get session attribute called uri I set in filter. BUT I when I try to use get attribute, Eclipse says there is no attribute called URI.
rd.forward(request,response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("login.html");
rd.include(request,response);
}
out.close();
}
}
And there is filter that I use to redirect to login page, when user is not signed in:
public class SessionFilter implements Filter{
// private ServletContext context;
public void init(FilterConfig filterConfig) throws ServletException {
//this.context = filterConfig.getServletContext();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI(); //THERE IS uri of the site from where the user gets redirected to login page
HttpSession session = req.getSession(false);
session.setAttribute("uri", uri); // HERE I TRY to set uri to session attribute. My intention is to use that uri in my login servlet
if(uri.endsWith(".css")) {
chain.doFilter(request, response);
return;
}
if(uri.endsWith(".js")) {
chain.doFilter(request, response);
return;
}
if(session == null && !(uri.endsWith("login.html") || uri.endsWith("login") || uri.endsWith("forgot.jsp") || uri.endsWith("signup.jsp"))){
res.sendRedirect("login.html");
System.out.print("redirecting to login");
}else{
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
Is it even possible, what I am trying to do? How to do it? Is there a better way to do it? I dont want to mix html and script. My intention is that, when user comes to a pages, and trys to get access to somewhere, he is redirected to login page. And after he logs in, he should be redirected to the page he wanted to go at the beginning.
Not sure if this would work but please try doing your filter like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
HttpSession currentSession = req.getSession(false);
if(uri.endsWith(".css")) {
chain.doFilter(request, response);
return;
}
if(uri.endsWith(".js")) {
chain.doFilter(request, response);
return;
}
if(currentSession == null && !(uri.endsWith("login.html") || uri.endsWith("login") || uri.endsWith("forgot.jsp") || uri.endsWith("signup.jsp"))){
HttpSession newSession = req.getSession();
newSession.setAttribute("uri", uri);
res.sendRedirect("login.html");
System.out.print("redirecting to login");
}else{
chain.doFilter(request, response);
}
}
What i did was create a new session in the filter if the session is null.