Form filling validation in Java - java

I do check in with a servlet, it works.
How validation of form filling?
For example, re-send the user to .jsp-file, if a username is already registered?
Sorry for bad english.

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// fetch the username that was sent in the request
String username = request.getParameter("username");
// TODO: verify if the username is taken in the database
// based on the results set the value
request.setAttribute("isUsernameTaken", "true");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/register.jsp");
dispatcher.forward(request, response);
}

Related

How to authenticate and create session programmatically in security context

Hi i have an application that uses its own implementation for user to authenticate ,by saving a User pojo in the HttpSession and invalidating that HttpSession Object when the session is done, but what i want to do is to use the security context to authenticate the user.
let's say that i have servlet AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
if(Authenticator.check(username,password)){
HttpSession session=req.getSession(true);
session.setAttribute("user",Authenticator.getUser(username));
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}else{
PrintWriter out= req.getWriter();
out.println("<h2>the password or username are incorrect</h2>");
}
}
the code above won't give me the power of security context so what i wan't is when i check that the user is ok to login tell in someway the security context that this user can access here are his roles
something like this inside my AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
LoginContext lc = new LoginContext("my-jaas",new MyCallbackHandler(username,password));
try{
lc.login();
//notice i have not save any thing in the HTTPSeession
//i want my container to remember this user like what happens in the
// form based authentication where nothing gets saved in the httpSession
// but the user keeps logged in(cartalina uses a session object not httpsession for that)
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}
catch(LoginException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}
i have created my own LoginModule ("my-jaas") and it works fine when i configure Form-Based authentication to work with it in tomcat7.
With Servlet 3.0, there is a login method in HttpServletRequest (https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)) so you can login like
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
try{
req.login(username, password);
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
} catch(ServletException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}

A href link is empty but the servlet is redirecting itself to home page.how it is done ?

//inboxservlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("uname");
PrintWriter out=response.getWriter();
out.println("welcome "+name);
out.println("<a href='SentItems?uname="+name+" '>sent items</a>");
out.println("<a href=''>Logout</a>");
}
If i click logout it redirects to login page.Help me with this
Try like this
Proper way to logout is below way:
out.println("Logout")
You have to create a servlet to call logout properly:
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("loginPage.jsp").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
out.close();
}
}
out.println("<a href=''>Logout</a>");
I believe your javascript code must be binding the event during page load time. See related javascript code.

Is it possible to redirect to the same JSP page from a Servlet?

A JSP page named Test.jsp is mapped to the following Servlet.
#WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public final class TestServlet extends HttpServlet
{
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//request.getRequestDispatcher("/WEB-INF/admin_side/Test.jsp").forward(request, response);
response.sendRedirect("TestServlet");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
This Servlet is mapped to a JSP page Test.jsp. The doGet() method is invoked, when a URL like http://localhost:8080/Assignment/TestServlet is entered in the address bar.
The request can be forwarded to the given URL as commented out. Is it possible to redirect to the same JSP page, Test.jsp?
If an attempt is made to do so, Google Chrome complains,
This webpage has a redirect loop
It can however, redirect to other pages under WEB-INF/admin_side.
The POST-REDIRECT-GET pattern works like so: a client sends a POST request, your server handles it and responds with a redirect, ie. a response with a 302 status code and Location header to the appropriate URI. The client makes a GET request to that URI.
Currently, your server is redirecting on both GET and POSTS requests. What's worse is that your GET is redirecting to the same URI that it is handling, creating the redirect loop you are seeing.
Change your Servlet implementation so that the POST sends a redirect, but the GET actually serves up a normal 200 response with HTML, AJAX, etc.

Session attributes getting lost

I am having a problem with a relativly easy thing. I am trying to do a simple program, where you can log in and log out using the session.
The session is created, but I am always getting forwarded to panel servlet and then to NoCorrectSession page. As if on login page the server saw isActive attribute, and then on panel page had not.
//class Login extends HttpServlet
private RequestDispatcher pageLogin, pagePanel, pageError; //defined in init()
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String name = request.getParameter("name");
String isBeingRequested = request.getParameter("isBeingRequested");
if (session.getAttribute("isActive") != null) {
//user has been logged in before, redirect him
pagePanel.forward(request, response);
} else if (isBeingRequested != null) {
//user has entered data into the login page and submitted it
if (name.length() == 0) {
//user has not stated his name
pageError.forward(request, response);
} else {
//otherwise access is granted and account created
session.setAttribute("isActive", "yes"); //setting session to active
pagePanel.forward(request, response);
}
} else {
//neither of these? user just entered the login screen
pageLogin.forward(request, response);
}
}
//class Panel extends HttpServlet {
private RequestDispatcher pageNoCorrectSession;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
//session has expired or never was started
if (session.getAttribute("isActive") == null) {
pageNoCorrectSession.forward(request, response);
//session valid
} else {
//logged in - do stuff
}
After digging in the project it turned out I've not made a mistake in these servlets, but in HTML code causing submitting a form directly to the panel servlet (and not creating the account object in the process). I know it is silly, but it was a great lesson. Expect the unexpected :P

How to check user authorized with filter

I have a filter and Login Servlet. How i can check - authorized user or not? and if not authorized - to redirect him to Login Servlet.
Thanks.
Do this:
When user logs in, set User object for that user in HttpSession. This way, httpRequest.getSession().setAttribute("LOGGED_USER", userObject)
Now, every time you hit the filter/security filter. The first thing you do is check for this attribute.
If the attribute is not there, redirect/forward the request to login servlet.
The pseudo code would look like this:
//in your login servlet, on successful login
request.getSession().setAttribute("LOGGED_USER", userObject);
//in your security filter
if(request.getSession().getAttribute("LOGGED_USER") == null){
//optionally, you may like to check if that attribute has a valid userId as well
RequestDispatcher rd = request.getRequestDispatcher("relative/path/to/login/servlet")
rd.forward(request, response);
return;
}
Edit 1: see this http://download.oracle.com/javaee/5/tutorial/doc/bncbx.html
In filter:
IF UserObjectInSession exists => user logged
ELSE do redirect to servlet
In servlet:
IF verification() will be correct => put UserObjectInSession to session
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
HttpSession session = httpReq.getSession();
User currentUser = (User)session.getAttribute("userInSession");
if (currentUser == null) {
httpRes.sendRedirect("...") //redirect to LoginServlet
} else {
chain.doFilter(request, response);
}
}

Categories