why this link works even after logout(or invalidate session)? - java

I have generated dynamic delete link for each row in a table in jsp. When I click on that link It should delete the associated row,It works Fine. But it should not delete the row once I logged out..I copied the delete link and logged out..Now If I run that link It redirects me to Login page, If I login again viewed the students in a table..It deletes that particular row.
Why this even after removed the attribute and invalidate the session It still able to reach the servlet?
generated link for delete student..
http://localhost:8080/feeManagement/Delete_Action_Student?delete=67657
Here are my DeleteStudent,Logout servlets.
#WebServlet("/Delete_Action_Student")
public class Delete_Action_Student extends HttpServlet {
private static final long serialVersionUID = 1L;
public Delete_Action_Student() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getAttribute("Accemail") != "") {
String id = request.getParameter("delete");
try {
if (StudentDAOimpl.removeStudent(id)) {
request.setAttribute("msg", "deleted successfully");
getServletContext().getRequestDispatcher("/Delete_Student").forward(request, response);
} else {
request.setAttribute("msg", "failed to remove");
getServletContext().getRequestDispatcher("/Delete_Student").forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
response.sendRedirect("/loginjsp.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Logout snippet.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("Accemail");
session.invalidate();
response.sendRedirect("loginjsp.jsp");
}

It's the behavior of browser to store the url where you came from to login page. So After successful login it redirect to that url.
After successful login if you want to land always to home page you can do that by using filter.

Related

back button goes to confirm form resubmission

I made a logout servlet for logout button, when clicking on logout servlet it successfully going to login page as coded. But when clicking on back button, it asks for form resubmission and after confirming it again going to previous user session.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/* PrintWriter out = response.getWriter(); */
HttpSession session = request.getSession();
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
response.setHeader("Cache-control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expire","0");
response.setDateHeader("Expires",-1);
session.invalidate();
String userr = (String)request.getAttribute("k");
if (userr == null)
response.sendRedirect("Login.html");
}
To anyone, who has a similar issue, here is the solution that worked for me.
Create your login.jsp page with the user input form (method should be POST)
<form action="${pageContext.request.contextPath}/userAuth" method="POST">
...
</form>
Create a filter class and map it to login.jsp. Inside the filter class make a check for null, retrieve session and check if it contains an attribute, which will signal that the user has already logged in (I used User object and mapped it as "user")
#WebFilter("/login.jsp")
public class AuthFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession();
if (session.getAttribute("user") != null) {
response.setContentType("text/html;charset=UTF-8");
request.getRequestDispatcher("homepage.jsp").forward(request, response);
}
chain.doFilter(request, response);
}
}
Create servlet class and map it to the form action inside login.jsp. Override doPost and doGet methods: former will contain user credentials processing logic, latter will contain log out logic.
#WebServlet("/userAuth")
public class AuthServlet extends HttpServlet {
/**
* Log in
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String email = request.getParameter("email");
String password = request.getParameter("password");
try {
User user = UserDAO.getUser(email, password);
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/login.jsp");
} catch (DAOException e) {
e.printStackTrace();
}
}
/**
* Log out
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.getSession().invalidate();
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect("login.jsp");
}
}
Create your homepage.jsp and add the logout button which will send GET to the servlet
Logout
Now the logic behind this is as follows:
The servlet doesn't actually redirect to user homepage. All it does is adding that one attribute, that the filter is looking for, and redirecting request back to login.jsp. And login.jsp always gets intercepted by the filter, who redirects to the homepage if that attribute is present.
This way you will solve the problem of keeping the user logged in until the session is on, as well as the problem of user being able to return or refresh page (which will cause form resubmission) after logging out. No additional headers like "no-cache" are needed.

Call a servlet to write data in JSON format to a URL in the server

I'm trying to call a Servlet that writes the javaobject taken from database in json format from another Servlet.
The flow of my code is Servlet1 check_login -> Servlet2 jsonCreate
I'm getting HTTP 404 error when I try to do that.
Here is my check_login.java Servlet code
#WebServlet("/Check_login")
public class Check_login extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user_name=request.getParameter("user_name");
String password=request.getParameter("password");
try {
String role=check_database(user_name,password);
if(role.equals("")) {
response.sendRedirect("index.html");
}else if(role.equals("admin")) {
List<Programs> Programs_Offered = new ArrayList<Programs>();
RequestDispatcher rd = request.getRequestDispatcher("jsonCreate");
rd.forward(request,response);
}else if(role.equals("mac")) {
response.sendRedirect("mac_welcome.jsp");
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
And, here is jsonCreate.java Servlet code
#WebServlet("/jsonCreates.json")
public class jsonCreate extends HttpServlet {
public static List<Programs> list() throws SQLException, IOException {
List<Programs> Programs_Offered = new ArrayList<Programs>();
Connection conn=DataBase_Connection.getInstance().getConnection();
Statement ps=conn.createStatement();
ResultSet rs = ps.executeQuery(Queries.view_programs);
while(rs.next()){
Programs p=new Programs();
p.setProgramName(rs.getString("ProgramName"));
p.setDescription(rs.getString("Description"));
p.setApplication_Eligibility(rs.getString("Applicant_Eligibility"));
p.setDuration(rs.getInt("Duration"));
p.setDegree_Certificate_Offered(rs.getString("Degree_Certificate_Offered"));
Programs_Offered.add(p);
}
return Programs_Offered;
}
private static final long serialVersionUID = 1L;
public jsonCreate() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Programs> categories=null;
try {
categories = jsonCreate.list();
} catch (SQLException e) {
e.printStackTrace();
}
String categoriesJson = new Gson().toJson(categories);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(categoriesJson);
//response.sendRedirect("admin_welcome.jsp");
}
when I make the name of jsonCreates.json same as java servlet Name (jsonCreate) it runs fine and opens the json data on page at URL http://localhost:8081/servlet_demo/jsonCreate.
Then again when I re-direct to a new JSP admin_welcome.jsp it opens without any problem but I don't find any json data available in the link http://localhost:8081/servlet_demo/jsonCreate.
I'm commiting some mistake and I'm not able to find it. Can someone tell what's missing in this.
You should set the name of jsonCreates.json same as java servlet Name (jsonCreate)
#WebServlet("/jsonCreate")
The reason why you dont get the json data is because response.sendRedirect() does not forward any data, it just makes a redirection(navigation) to a page.
If you want your JSON data to be accessible throughout your page navigations then you should create a session and set a session variable to hold this json data.
JAVA
HttpSession session = request.getSession(false);
session.setAttribute("variable", "json value");
response.sendRedirect("/page");
JSP
<%
out.println(session.getAttribute("variable"));
%>
OR
you can use forward() as below:
JAVA
request.setAttribute("variable", "JSON data");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
JSP
<%
out.println(request.getAttribute("variable"));
%>

FreeMarker : Displaying a custom 404 page without redirection

I have a static 404 page with fancy stuff in it.
In case the user enters a wrong url of a page that does not exist, I would like him to see that 404 page , but also would like to keep the url as is in order for user to see what mistake s/he has done typing the url .
The page entered and that does not exist :
http://localhost:10039/my.website/my/halp.html
The 404 page :
http://localhost:10039/my.website/my/notfound.html
Briefly, instead of using "sendRedirect" here, I would to "get content" of pageNotFoundUrl and show it while the url is still http://localhost:10039/my.website/my/halp.html
Instead of redirect, I also tried "forward" as Kayaman suggested but in this case I get " Cannot forward. Response already committed."
TestServlet is defined in web.xml , and this class extends UtilFreemarkerServlet which extends FreemarkerServlet.
UtilFreemarkerServlet
public abstract class UtilFreemarkerServlet extends FreemarkerServlet {
private static final long serialVersionUID = 1L;
public static final String REQUEST_OBJECT_NAME = "RequestObject";
private Logger logger = LoggerFactory.getLogger(getClass());
#Override
public void init() throws ServletException {
logger.info("init started");
super.init();
Configuration cfg = getConfiguration();
cfg.setLocalizedLookup(false);
}
#Override
protected ObjectWrapper createObjectWrapper() {
return ObjectWrapper.BEANS_WRAPPER;
}
#Override
protected HttpRequestParametersHashModel createRequestParametersHashModel(HttpServletRequest request) {
request.setAttribute(REQUEST_OBJECT_NAME, request);
return super.createRequestParametersHashModel(request);
}
}
TestServlet
public class TestServlet extends UtilFreemarkerServlet{
private static final long serialVersionUID = 1L;
private String website;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
boolean handleResult = handlerForRequest(req, resp);
}
protected boolean handlerForRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (resp.getStatus() == 404) {
String pageNotFoundUrl = "http://localhost:10039/my.website/my/notfound.html";
RequestDispatcher rd = req.getRequestDispatcher(url);
rd.forward(req, resp);
// resp.sendRedirect(url);
}
return true;
}
}
Do a forward instead of a redirect to the wanted resource, and the URL will stay the same.
RequestDispatcher rd = request.getRequestDispatcher("my_404.html");
rd.forward(request, response);
RequestDispatcher is not useful in my case because the response has always been committed. Here is the solution I end up with for Freemarker Servlets;
I am overriding a couple of methods of Freemarker servlet for my purpose such as service() and requestUrlToTemplatePath(). By this way, I am able to interfere right before the response is committed.
First Override is for the service method. My purpose is to check if the requested url page exists or not.
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
checkIfPageExists(req);
super.service(req, resp);
}
checkIfPageTemplateExists checks if the template of the page is null or not. If null, then it means it is not available. In this case I set a request attribute. Otherwise, it means it exists.
protected void checkIfPageExists(HttpServletRequest req)
throws ServletException {
String relativeUrl = requestUrlToTemplatePath(req);
try {
getConfiguration().getTemplate(relativeUrl); //throws exception if the template cannot be accessed
} catch (TemplateNotFoundException e) {
logger.debug("TemplateNotFoundException for " + relativeUrl);
pageNotFound = "/customNotFoundPage.html";
} catch (IOException e) {
logger.debug("IOException for " + relativeUrl);
pageNotFound = "/customNotFoundPage.html";
}
req.setAttribute(NOT_FOUND_PAGE, pageNotFoundPage);
}
And the last line stated in bullet 1 is for super.service() method. This will trigger the requestUrlToTemplatePath() method which is actually the method you can specify what url page to be shown without changing the url.
I am just checking if the request has a NOT_FOUND_PAGE attribute. If so, just overwrite the path itself and move on to the next step in the flow. Otherwise, just use the path of super class.
#Override
protected String requestUrlToTemplatePath(HttpServletRequest request)
throws ServletException {
String path = super.requestUrlToTemplatePath(request);
//Check if NOT_FOUND_PAGE is requested
if(request.getAttribute(NOT_FOUND_PAGE) != null) {
path = (String) request.getAttribute(NOT_FOUND_PAGE);
}
return path;
}

Why is the code not reaching else part

In this servlet,the code is never reaching the else part why so?even though i have not added any cookies and it is still printing some random value?Why so?
public class profile extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Cookie[] ck=req.getCookies();
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
if(ck!=null)
{
System.out.println("hello");
RequestDispatcher rd=req.getRequestDispatcher("/index.jsp");
rd.include(req, resp);
out.println("welcome to your profile "+ck[0].getValue());
}
else
{
out.println("sorry annonymous,you have to login first");
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
}
}
and even eclipse was saying dead code why so?
Instead of verifying existance of cookies.
You should verify some exact value, that you can prevously set with setCookies method.

How do I get and pass the JSESSIONID into another method

To begin I am a bit new to java.
I have a web application I have been assigned to work on. It collects various user inputs via form and sends them via an a4j commandButton to a method in my jar folder. The method uses the form data to construct a web service client call. Part of the requirement is that I pass, as an element in the web service call, the current JSESSIONID from the request.
Steps I have taken:
In the class that contains the method I am calling I have set up getters and setters (outside of the helper class below).
I have added a helper class to my class as follows:
class GetSessionId extends HttpServlet {
private String sessionid;
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
sessionid = session.getId();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public String getSessionId(){
return sessionid;
}
public void setSessionId(String sessionid){
this.sessionid=sessionid;
}
}
When I need the get the sessionid I used:
GetSessionId session_ID = new GetSessionId();
String sessionid = session_ID.getSessionId();
String sessionId = sessionid;
System.out.println("show me = " + sessionId);
But in the console (testing on my localhost) sessionid is null.
What am I doing wrong?

Categories

Resources