How pass value from a method to another in a servlet - java

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);
}

Related

Servlet gives a blank page when it should be redirecting

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)

StandardWrapperValve[web.dbServlet]: Servlet.service() for servlet web.dbServlet threw exception java.lang.NullPointerException

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 am working on servlets, having only one deGet and DoPost method. i wrote one new method in that. . how can i access that new method directly?

I have call this method under doGet. Please help me to get out of this.
This is my own method and I wanted to call this.
public void doYourThingHere(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String[] checkedQues = request.getParameterValues("ttom");
List<String> checkedQuesList = Arrays.asList(checkedQues);
Map<String, String> preferences = new LinkedHashMap<String, String>();
if (session.getAttribute("username") != null) {
List<Question> questionsList = (List<Question>) session
.getAttribute("restaurantQuestionList");
List<Question> questionsListTemp1 = new ArrayList<>();
for (int i = 2; i < 4; i++) {
questionsListTemp1.add(questionsList.get(i));
}
session.setAttribute("tomtomRestaurantQuestionList1",
questionsListTemp1);
for (Question question : questionsList) {
String questionId = String.valueOf(question.getId());
if (checkedQuesList.contains(questionId)) {
String answerId = request.getParameter(questionId);
// PreferenceDAO.storePreferences(questionId, answerId,
// CATEGORY);
preferences.put(questionId, answerId);
System.out.println("queid : " + questionId + "answerid : "
+ answerId);
}
}
String username = (String) session.getAttribute("username");
PreferencesProcessor.process(preferences, username);
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/table.jsp");
requestdp.forward(request, response);
} else {
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/login.jsp");
requestdp.forward(request, response);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
/**
* #see HttpServlet doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
Servlets map HTTP request headers to predefined methods, such as doGet(), doPost(), and some others.
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServlet.html
Since your method modifies data, you should call it with POST.
Most simple way is to forward your doPost() to this method:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
doYourThingHere(request, response);
}
What will happen usually is that you'll add some routing logic to your doPost like that:
public void doPost(...) {
String action = request.getParameter("action");
switch (action) {
case "doSomething":
doSomething(request, response);
break;
case "somethingElse":
doSomethingElse(request, response);
break;
...
}
}

How to test non-Spring controllers using Spring test framework

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);
}
}

java.lang.IllegalStateException: Cannot forward after response has been committed in servletfilter

I am using a filter to determine whether or not a requested page has a valid session or not.
This is my code. web.xml:
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>
com.imagemanagementutility.filter.SessionFilter
</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter class:
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
System.out.println(url.replace("/",""));
if (urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("redirect in servlet session filter");
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
}
chain.doFilter(req, res);
System.out.println("end");
}
public void init(FilterConfig config) throws ServletException {
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
}
I have a login page which is used to check whether or not the user is valid.
If the user is valid then control is transfer to this servlet.
public class MainService extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(MainService.class.getName());
/**
* #see HttpServlet#HttpServlet()
*/
public MainService() {
super();
}
/*
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html;charset=UTF-8");
LogUtil.logInfo("i m here");
List<Images> imageList = null;
response.setContentType("text/html");
try {
UserDataService userDataService = new UserDataImpl();
String userId = null;
String username = null;
String password = null;
username = request.getParameter("user");
password = request.getParameter("password");
userId = userDataService.checkUser(username, password);
if (userId!=null) {
System.out.println(userId);
session.setAttribute("userId", userId);
imageList = userDataService.getImages(userId);
session.setAttribute("imageList", imageList);
/*response.sendRedirect("//showUserImages.jsp");*/
RequestDispatcher dispatcher = request
.getRequestDispatcher("//showUserImages.jsp");
dispatcher.forward(request, response);
} else {
/*response.sendRedirect("//index.jsp");*/
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
} catch (ImageException e) {
e.getMessage();
e.printStackTrace();
}
}
}
This works without the filter, but with the filter shows an error
when I forward control to "//showuserImages.jsp".
Put the invocation of doFilter in an else block:
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("redirect in servlet session filter");
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
}else{
chain.doFilter(req, res);
}

Categories

Resources