How to test jakarta servlet using JUnit and Mockito? - java

I have simple servlet, how to check if the message has been displayed?
#WebServlet(name = "helloWorld", value = "/hello.world")
public class HelloWorld extends HttpServlet
{
private String message;
public void init()
{
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter out = response.getWriter();
out.println(message);
}
}

Related

Java SSE method in doGet() not working

I wrote a method which return an Array converted as String. When calling this method in the main method and printing it out the array is filled. When I am calling the same method in the doGet method for printing it in my html file, the array is empty and it prints only: []
Normally the doGet method schould work because when the method return not the array but just "hello" the html file print the String.
Here ist the code:
public static String test(senderonpremise s){
String t;
//this should be printed
t = String.valueOf(s.arrivalList);
//startSending();
//this works in doGet()
//return "this works";
// when I return this it works in the main-method but not in DoGet()
return t;
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/event-stream");
resp.setCharacterEncoding("UTF-8");
senderonpremise s = new senderonpremise();
PrintWriter out = resp.getWriter();
String next = "data: " + test(s) + "\n\n";
out.write(next);
out.flush();
}
/**
public static void main(String[] args) {
senderonpremise s = new senderonpremise();
System.out.print(test(s));
}
**/
I recommend you using the JEaSSE library: https://github.com/mariomac/jeasse, which is lightweight and works out of the box with Servlets 3.x
#WebServlet(asyncSupported = true)
public class ExampleServlet1 extends HttpServlet {
EventTarget target;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
target = new ServletEventTarget(req).ok().open();
}
public void onGivenEvent(String info) {
target.send("givenEvent",info);
}
}

init method is calling again and again in servlet

The init method gets called again and again on every request in servlet.
Here is the code:
public class PersonInfoController extends HttpServlet {
private static final long serialVersionUID = 1L;
public PersonInfoController() {
super();
}
public void init() throws ServletException {
Connection connection = Database.getConnection();
System.out.println("init method");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<PersonInfoServiceI> myList = new ArrayList();
PersonInfoServiceI instance = new PersonInfoServiceImpl();
myList = instance.getdata();
String jsonstring = new Gson().toJson(myList);
request.setAttribute("List", jsonstring);
RequestDispatcher rd = request.getRequestDispatcher("showdata.jsp");
rd.forward(request, response);
}
public void destroy() {
System.out.println("the destory");
}
}
According to your code init() should call only once when servlet will load on first request. Then after its destruction init() will be called again on new request. In between only your service method will be called. Your code is good having no logical mistakes.
Are you calling init method outside the servlet?
Can you attach you deployment descriptor?

java servlet submit button doesn't work

I'm been writing a small login servlet. The login part works just fine, but when I press logout submit button - nothing happens.
Servlet code down bellow:
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7638796169158385551L;
private Database database = Database.getInstance();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.write("<html><head><title>Login form</title></head>");
if (!database.connected) {
outLoginForm(out);
} else {
out.write("Hello " + database.getLoginName() + "!");
outLogoutForm(out);
}
out.write("</body></html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("loginsub") != null) {
if (isParameterEmpty(request, "login")
|| isParameterEmpty(request, "pass")) {
response.getWriter().write("Some fields are empty");
doGet(request, response);
}
try {
database.connect(request.getParameter("login"),
request.getParameter("pass"));
} catch (ExceptionInInitializerError ex) {
response.getWriter().write("Login or password is incorrect");
}
} else if (request.getParameter("logoutsub") != null) {
database.disconnect();
}
doGet(request, response);
}
private boolean isParameterEmpty(HttpServletRequest request,
String parameter) {
if (request.getParameter(parameter).isEmpty())
return true;
return false;
}
protected void outLoginForm(PrintWriter out) {
out.write("<FORM method =\"POST\">");
out.write("Login:<input type=\"text\"name=\"login\"><br>");
out.write("Password:<input type=\"password\"name=\"pass\"><br>");
out.write("<input type=\"submit\"name=\"loginsub\" value=\"Login\"/><br>");
out.write("</FORM><br>");
}
protected void outLogoutForm(PrintWriter out) {
out.write("<FORM method =\"POST>\">");
out.write("<input type=\"submit\"name=\"logoutsub\" value=\"Logout\"/><br>");
out.write("</FORM><br>");
}
}
Can anyone help me find out what's wrong? I'm new to JSP and java servlets.
There is one problem is below line (one extra > after POST
out.write("<FORM method =\"POST>\">");
replace it with
out.write("<FORM method =\"POST\">");

Servlet filter wrapper - trouble changing content type

I have RESTful web service which is consumed by javascript. This service returns a content type of "application/json". However, for IE the content type must be "text/html". So I written a filter and wrapper to change the content type when IE is detected as the client. My logic seems to have no effect on the content type. What am I doing wrong?
The filter:
public class IE8Filter implements Filter {
private Logger logger = LoggerHelper.getLogger();
#Override
public void destroy() {}
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String userAgent = request.getHeader("User-Agent");
logger.debugf("User Agent = '%s'", userAgent);
IE8FilterResponseWrapper wrapper = new IE8FilterResponseWrapper(response);
chain.doFilter(req, wrapper);
if (userAgent.contains("MSIE 8") || userAgent.contains("MSIE 7")) {
wrapper.setContentType("text/html");
logger.debugf("Content Type = '%s'", wrapper.getContentType());
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
The wrapper:
public class IE8FilterResponseWrapper extends HttpServletResponseWrapper {
private String contentType;
public IE8FilterResponseWrapper(HttpServletResponse response) {
super(response);
}
public void setContentType(String type) {
this.contentType = type;
super.setContentType(type);
}
public String getContentType() {
return contentType;
}
}
I found an answer. The trick was to prevent my web service from setting the content-type using my wrapper:
public class IE8FilterResponseWrapper extends HttpServletResponseWrapper {
public IE8FilterResponseWrapper(HttpServletResponse response) {
super(response);
}
public void forceContentType(String type) {
super.setContentType(type);
}
public void setContentType(String type) {
}
public void setHeader(String name, String value) {
if (!name.equals("Content-Type")) {
super.setHeader(name, value);
}
}
public void addHeader(String name, String value) {
if (!name.equals("Content-Type")) {
super.addHeader(name, value);
}
}
public String getContentType() {
return super.getContentType();
}
}
And my filter now looks like:
public class IE8Filter implements Filter {
private Logger logger = LoggerHelper.getLogger();
#Override
public void destroy() {}
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String userAgent = request.getHeader("User-Agent");
logger.debugf("User Agent = '%s'", userAgent);
IE8FilterResponseWrapper wrapper = new IE8FilterResponseWrapper(response);
if (userAgent.contains("MSIE 8") || userAgent.contains("MSIE 7")) {
wrapper.forceContentType("text/html");
chain.doFilter(req, wrapper);
}
else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
I'm not sure if this was how wrappers were intended to be used but heck it works.

Can I implement HttpSessionListener this way?

I'm trying to tracking valid user Ids in my Java servlet, can I implement HttpSessionListener this way ?
public class my_Servlet extends HttpServlet implements HttpSessionListener
{
String User_Id;
static Vector<String> Valid_User_Id_Vector=new Vector<String>();
private static int activeSessions=0;
public void sessionCreated(HttpSessionEvent se)
{
// associate User_Id with session Id;
// add User_Id to Valid_User_Id_Vector
Out(" sessionCreated : "+se.getSession().getId());
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se)
{
if (activeSessions>0)
{
// remove User_Id from Valid_User_Id_Vector by identifing it's session Id
Out(" sessionDestroyed : "+se.getSession().getId());
activeSessions--;
}
}
public static int getActiveSessions()
{
return activeSessions;
}
public void init(ServletConfig config) throws ServletException
{
}
public void destroy()
{
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
User_Id=request.getParameter("User_Id");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
public String getServletInfo()
{
return "Short description";
}
}
How to get the listener notified when a session ends ? I'm trying to bypass "/WEB-INF.web.xml" all together, is it doable ? Or does it make sense ?
This won't bypass /WEB-INF/web.xml. Furthermore, you'll end up with 2 instances of this class, not 1 performing both functions. I suggest you put this Vector in the ServletContext and have 2 separate classes.
In the servlet, you get to it via getServletContext(). In the listener, you'll do something like this:
public void sessionCreated(HttpSessionEvent se) {
Vector ids = (Vector) se.getSession().getServletContext().getAttribute("currentUserIds");
//manipulate ids
}

Categories