I am getting HTTP Status 404 - /ShowForm this error pls help me to solve this.
ShowForm.html
<form action = "/ShowForm" method = "post" enctype="multipart/form-data" >
Name: <input type = "text" name = "name" /><br>
File: <input type = "file" name = "file" /><br>
<input type = "submit" value = "submit" name = "submit">
</form>
ShowForm.java
#WebServlet("/ShowForm")
public class ShowForm extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowForm() {
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
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/plain");
PrintWriter pw = response.getWriter();
ServletInputStream sis = request.getInputStream();
for(int i = sis.read();i != -1;i = sis.read())
{
pw.print((char)i);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Here I am using Annotation so I have not map in web.xml.
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)
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;
...
}
}
this is my servlet: json array have objects "esquina". esquina have two attributes double coordX and double coordY
package servlets;
#WebServlet("/Mapa")
public class ServletMapa extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServletMapa() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
JSONObject jO = null;
for (Esquina esquina : esquinas) {
jO = new JSONObject(esquina);
json.put(jO);
System.out.println(json);
}
request.setAttribute("esquinas", esquinas);
request.setAttribute("json", json);
request.getRequestDispatcher("/gui/Mapa.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
i need to get the data from jsonArray to jquery, i tried getJSON() function , but didnt work.
hereĀ“s the code
function cargarMarcadores() {
var x=$("#iniSistema");
x.click(function(){
$.getJSON('localhost:8080/Carpuleame/Mapa',function(data){
alert("data");
});
});
}
there are antoher way to do it ?
You probably want something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
for (Esquina esquina : esquinas) {
JSONObject jO = new JSONObject();
jO.put("coordX", esquina.getCoordX());
jO.put("coordY", esquina.getCoordY());
json.put(jO);
}
// tell the client that JSON is coming
response.setContentType("application/json");
resposne.setCharacterEncoding("UTF-8");
json.write(response.getWriter());
}
There are a bunch of frameworks that'll take away a lot of the "brute-force"-iness of this code, but this is very close to your starting position.
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.
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);
}
}