Load image name ussing session - java

I am doing some test, and I want to use java servlet session to remember the images that the user has already seen and to only print out the image names of the images that the user haven't already seen. For example, if the Images=2 I should only it should display img1.png, img2.png and if Images=3 it should only display img3.png because names img1.png, img2.png was already displayed. my code work, but I am not sure how the set the sessions so that I work like what I was expecting.
http://localhost:8080/XXXX/test?Images=3
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
public class ImageServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
File imagePath=new File(getServletContext().getRealPath("/images"));
File[] imageFiles=imagePath.listFiles();
String Imagesname=req.getParameter("Images");//geting Images from index.html
int result = Integer.parseInt(Imagesname);
for (int i = 0; i < result; i++) {
if(session.isNew()){
out.print(imageFiles[i].getName());
}else{
out.print("welcome back");
}
}
}
}

Set
HttpSession httpSession = ServletActionContext.getRequest().getSession();
httpSession.setAttribute("img","yourname");
Get
HttpSession httpSession = ServletActionContext.getRequest().getSession();
String name = (String) httpSession.getAttribute("img");

Related

changing URL but want to send data to controller

My web application has a new requirement that if parameter coming in url then land to email page. otherwise on index page like always.
Its a very old client product and not much scope to change lot in code so i put a check in controller that if encrypted email coming in then land to email page.
example url -
http://localhost:8080/R2/Controller?email=jAOtTv22BfkTkVrhTN/RHQ==
Everything works fine but i want to change URL.
How can i get rid of " /Controller " in URL but still it hits to controller.???
Controller code like -
public class Controller extends HttpServlet {
static Logger logger = Logger.getLogger(Controller.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// get the action property from the request
String theAction = request.getParameter("action");
String theSource = request.getParameter("s");
String theSource1 = request.getParameter("email");
String em ="";
Action action=null;
em = EncryptEmail.decrypt(theSource1,GFWConstants.BLOWFISH_KEY);
if (em.equals(""))
rd = request.getRequestDispatcher("index.jsp?emailRtv=0");
else
rd = request.getRequestDispatcher("email-preferences.jsp?emailRtv=2&emailAddress="+em);
rd.forward(request,response);
return;
}
Thanks in advance.
adding two url-pattern to web.xml file worked.

Declare a session variable golbaly to access from DoGet and DoPost in a sevlet

I have a servlet where I need to declare a session which can be acceptable form doGet and doPost both how I should do this?
I have done
#WebServlet(name = "LoginLogout", urlPatterns = {"/LoginLogout.do"})public class LoginLogout extends HttpServlet {//For Session
HttpSession session = request.getSession(true);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String status = request.getParameter("status");
System.out.println(status);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String loginId = request.getParameter("login_id");
String password = request.getParameter("password");
System.out.println(loginId);
//Inserting value to the Pogo named "newLoginPogo"
loginData newLoginPogo = new loginData();
newLoginPogo.setLoginId(loginId);
newLoginPogo.setPassword(password);
//Creating a obj of ModelLogin to send the loginId and Password via a method which is in ModelLogin class
ModelLogin loginBis = new ModelLogin();
loginData userData = loginBis.checkUser(newLoginPogo);
String userExist = userData.getUserExist();
System.out.println(userExist);
if ("yes".equals(userExist)) {
System.out.println("In while loop of Servlet");
String firstName = userData.getFirstName();
String userId = userData.getUserId();
boolean IsSu = userData.getIsSu();
//conveting boolean to string
String superuser = new Boolean(IsSu).toString();
//Creating a session
session.setAttribute("firstName", firstName);
session.setAttribute(userId, "userId");
session.setAttribute(superuser, "IsSu");
//==============================================================================================================
//If user does exist show the Success Message and forward Dashboard
//==============================================================================================================
//Session for success message
String succmsg = "Login Successful";
session.setAttribute("succmsg", succmsg);
getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/ViewPages/dashboard/dashboard.jsp").forward(request, response);
} //==============================================================================================================
//If user does not exist show the Error Message
//==============================================================================================================
else if ("no".equals(userExist)) {
//Session for success message
System.out.println("inside NO");
String emsg = "Login Error";
session.setAttribute("errmsg", emsg);
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} else {
}
/*
//===============================================================================================================
//code for Logout
//===============================================================================================================
String status = request.getParameter("status");
if ("logout".equals(status)) {
//clearing the session
session.invalidate();
//forwarding to index page
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
*/
} finally {
}
}}
But it says
Can Not find Symbol
in this line HttpSession session = request.getSession(true);
You don't need to have session variable in servlet as field. In general - this is kind of common mistake. There will be only one onstance of servlet serving lots of requests, and unless you declare it as single-threaded - the requests would be handled concurrently.
HttpSession will be pre-exist for you in doGet and doPost via request object. Servlet container will guarantee this. So simply obtain reference to the session in doGet/doPost and do whatever you want.
What you desire is one of the roles of HTTP session.
You can look at it as a conversation between the client and the server.
As long as the "conversation" (HTTP session) is open and alive, you can set variables on the HTTP session, and access them from different requests that will sent on the same session.
Look at this as some sort of "shared memory" that exists during the "conversation time".
You can find many examples on how to do that over the internet.
Here is an example for session tracking.

Redirect saving POST parameters using HTTP

I have 2 web-pages.
So, 1st page takes some POST parameters, and then process it. I want to redirect this query(with all POST params) to my own 2nd page, if parameter "appId" = "myApp";
In start of 1st page I make next:
if (getParameter("id") == "myApp")
{
request.setHttpHeader("") - ??? WHAT MUST BE HERE? WHICH HEADERS?
}
P.S. I need only HTTP solution, using native (java) methods (like forward and redirect) don't help me.
Thanks.
You have to user RequestDispatcher.forward. Here is an example.
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
/*
* You can do any processing here.
* We will simply output the value of name parameter on server console.
*
*/
System.out.println(name);
String destination = "/DestinationServlet";
RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
rd.forward(request, response);
}
}
What you're asking for can't be done with pure HTTP. You can only redirect GETs with HTTP. See this answer to a similar question https://stackoverflow.com/a/1310897/116509

Get client environment information by cookies

I just started with Java servlets few days ago. I am trying to develop a program just for practice and to get to know the the stuff we can do with Java servlets.
Trying to have a program that generates a cookie and sends it back to the client in response.
Sending back the cookie and getting cookie info back is fine, but what I want to do is that can we get information about the clients environment using cookies as well as can we get the browser information using cookies, such as which browser, its version, OS, etc.
I know they store state information since HTTP is stateless. So I was just wondering and trying is there a way to get client's environment information and browser information by cookies in servlets.
Cookies are not designed to get client information. You have to use javax.servlet.http.HttpServletRequest methods - getHeader() or getHeaders() method to read request header key-value.
Enumeration names=request.getHeaderNames();
while(names.hasMoreElements())
{
String key=names.nextElement().toString();
String value=request.getHeader(key);
}
Want to get value of user-agent key.
String userAgent=request.getHeader("user-agent");
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}
Please visit this link

Java servlet and server sent events

Is it possible to create a server sent event using java servlets so that a client could receive updates using:
<script>
var source = new EventSource('/events');
source.onmessage = function(e) {
document.body.innerHTML += e.data + '<br>';
};
</script>
All examples I have found on the web are using PHP but I would assume that it should work using Java's HTTP Servlet.
this does the trick.
HTML
<!DOCTYPE html>
<html>
<body onload ="registerSSE()" >
<script>
function registerSSE()
{
alert('test 1');
var source = new EventSource('http://frewper:8080/hello/sse');
alert('Test2');
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
/*source.addEventListener('server-time',function (e){
alert('ea');
},true);*/
}
</script>
<output id ="result"></output>
</body>
</html>
Servlet :
import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class sse extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
System.out.println("SSE Demo");
response.setContentType("text/event-stream");
PrintWriter pw = response.getWriter();
int i=0;
while(true)
{
i++;
pw.write("event: server-time\n\n"); //take note of the 2 \n 's, also on the next line.
pw.write("data: "+ i + "\n\n");
System.out.println("Data Sent!!!"+i);
if(i>10)
break;
}
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
doPost(request,response);
}
}
Server-Sent Events is a HTML5 feature. We say "HTML5", therefore it's just client side feature.
So long server can set https respnse header "text/event-stream;charset=UTF-8","Connection", "keep-alive", then it is supported by server. You can set such header with Java Servlet.
Here you can find a step for step guide on SSE with servlet
I have created a very simple library that can be integrated within plain Java Servlets in Asynchronous mode, so no extra server threads are required for each client: https://github.com/mariomac/jeasse
It integrates the SseDispatcher (for point-to-point SSEs) and SseBroadcaster (for event broadcasting). An example of use:
public class TestServlet extends HttpServlet {
SseBroadcaster broadcaster = new SseBroadcaster();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Scanner scanner = new Scanner(req.getInputStream());
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine());
}
System.out.println("sb = " + sb);
broadcaster.broadcast("message",sb.toString());
}
//http://cjihrig.com/blog/the-server-side-of-server-sent-events/
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
broadcaster.addListener(req);
}
}

Categories