Can anybody please provide me some guidance or code sample on how to do this?
HomePageController.java
public class HomePageController extends HttpServlet {
private static final Logger log = Logger.getLogger(HomePageController.class);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#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);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Into the HomePageController...");
showPage(request, response, HOME_PAGE_URL);
}
private void showPage(HttpServletRequest request, HttpServletResponse response, String viewName) throws ServletException, IOException {
log.debug("Displaying " + viewName + " page now...");
String url = TEMPLATE_PAGE_URL + "?gotoPage=" + viewName;
//forward the request to the page
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
}
Related
I'm having a problem in my servlet ("maakservlet"), the maakservlet should redirect automatically to welkom.jsp but instead it just gives me a blank page.
I have tried requestdispatches, response.sendRedirect etc.
Here is my code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int code = 1;
String voornaam = request.getParameter("voornaam");
String achternaam = request.getParameter("achternaam");
String eerstebezoek = request.getParameter("eerstebezoek");
String meerderebezoeken = request.getParameter("meerderebezoeken");
String attractie = request.getParameter("attractie");
String naamattractie = request.getParameter("naamAttractie");
String naampretpark = request.getParameter("naampretpark");
Bezoeker bezoeker = new Bezoeker(voornaam, achternaam);
if (attractie == "geen") {
;
} else {
bezoeker.voegToeAanWishlist(attractie);
}
if (eerstebezoek == null && meerderebezoeken == null) {
bezoeker.setPretparkcode(1000);
} else if (meerderebezoeken != null) {
bezoeker.setPretparkcode(code);
code += 1;
}
String destination = "welkom.jsp";
RequestDispatcher requestDispatcher = request.getRequestDispatcher(destination);
}
#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);
String welkom = "welkom.jsp";
response.sendRedirect("welkom.jsp");
RequestDispatcher rd = request.getRequestDispatcher("welkom.jsp");
rd.forward(request, response);
}
To redirect the request to a completely different page you have to use your response:
response.sendRedirect(destination);
See: https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)
private void ajouterActeurFilm(HttpServletRequest request, HttpServletResponse response) throws Exception {
String nom= request.getParameter("acteurRecherche");
ArrayList<Celebrite> listeActeurs= dao.RechercherActeur(nom);
RequestDispatcher dispatcher
= request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
dispatcher.forward(request, response);
}
private void ajouterActeur(HttpServletRequest request, HttpServletResponse response) throws Exception {
String id=request.getParameter("idMedia");
RequestDispatcher dispatcher
= request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
dispatcher.forward(request, response);
}
I would like to know if is possible to pass the value id from the method ajouterActeur to ajouterActeurFilm.
You can set the value like:
private void ajouterActeur(HttpServletRequest request, HttpServletResponse response) throws Exception {
String id = request.getParameter("idMedia");
request.setAttribute("id",id);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
dispatcher.forward(request, response);
}
And you can get the value as:
private void ajouterActeurFilm(HttpServletRequest request, HttpServletResponse response) throws Exception {
String nom = request.getParameter("acteurRecherche");
ArrayList<Celebrite> listeActeurs = dao.RechercherActeur(nom);
String id = (String) request.getAttribute("id");
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/AjouterActeurFilm.jsp");
dispatcher.forward(request, response);
}
I try to insert some information in the table, but get such an error (NullPointerException). Maybe it causes of empty request, but I'm not sure.
Here is a log with error:
enter image description here
First Servlet:
#WebServlet("/clientServlet")
public class clientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Client client = new Client();
client.setName(request.getParameter("name"));
client.setSurname(request.getParameter("surname"));
HttpSession session = request.getSession();
session.setAttribute(sessionKey.client, client);
response.sendRedirect("addTour.html");
}
The second one:
#WebServlet("/tourServlet")
public class tourServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Tour tour = new Tour();
tour.setCountryTo(request.getParameter("countryTo"));
tour.setAmountOfDays(request.getParameter("amountOfDays"));
session.setAttribute(sessionKey.tour, tour);
response.sendRedirect("final.jsp");
}
Problem appears in this Servlet:
#WebServlet("/dbServlet")
public class dbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public dbServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
IRepositoryCatalog catalog = new RepositoryCatalog("jdbc:hsqldb:hsql://localhost/workdb");
HttpSession session = request.getSession();
Client client = (Client) session.getAttribute(sessionKey.client);
Tour tour = (Tour) session.getAttribute(sessionKey.tour);
catalog.Clients().add(client);
catalog.saveAndClose();
catalog.Tours().add(tour);
catalog.saveAndClose();
catalog.saveAndClose();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException a) {
a.printStackTrace();
}
}
At first impression i can say that maybe the first and second servlet are for a POST method so doing a doGet and trying to 'getParameter' you will get empty object and so throw a NullPointerException. Can you post something about your view?
(I would comment but i can't yet)
i just installed Tomcat via Netbeans and created a new project. I just want to print some text on screen but only "Hello World!" is shown. Do i have to something specific to show text on screen?
EDIT: [SOLVED] I do not know what the problem was. I just changed my IDE from Netbeans to Eclipse, now everything works.
System: Ubunut 16.04 LTS 64Bit
#WebServlet(name = "MicStreamReciever", urlPatterns = {"/MicStreamReciever"})
public class MicStreamReciever extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("processRequest");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("doGet");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
I am trying to test my servlet for login page but the Mock test is throwing an exception
LoginServlet
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession(true);
boolean result = false;
String username = request.getParameter("username");
String password = request.getParameter("password");
result = obj.validateLogin(username, password);
if (result) {
session.setAttribute("username", username);
response.sendRedirect("UserHome.jsp");
} else {
response.sendRedirect("login.jsp");
}
return;
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
MockTest : this is the test case I have written for login
public class LoginServletMockTest {
#Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
HttpSession session = request.getSession(true);
when(request.getParameter("username")).thenReturn("garwitauday");
when(request.getParameter("password")).thenReturn("123");
when(request.getSession()).thenReturn(session);
doNothing().when(session).setAttribute("username", "garwitauday");
doNothing().when(response).sendRedirect("Userhome.jsp");
LoginServlet loginservlet = new LoginServlet();
loginservlet.doPost(request, response);
verify(session).setAttribute("username", "garwitauday");
verify(response).sendRedirect("Userhome.jsp");
}
}
I am not able to resolve this issue
Create the mockito object for HttpSession also and set the mockito session object in request.
And continue your same do(..).when(..) or when(..).thenReturn(..) to mock the calls.
Make sure to set the attributes and parameters in request and session objects for easy testing.
If your's is mvc based servet, better to use MockMvc and it's builder objects.