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.
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 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 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;
...
}
}
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.
I want to do some log in my system, like user action,
and I know in the servelet I can get the request with all the session,parameter..etc
So I want to write the Servlet
public class UserActionCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Map map = request.getParameterMap();
Set keSet = map.entrySet();
for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
Map.Entry me = (Map.Entry) itr.next();
Object ok = me.getKey();
Object ov = me.getValue();
String[] value = new String[1];
if (ov instanceof String[]) {
value = (String[]) ov;
} else {
value[0] = ov.toString();
}
for (int k = 0; k < value.length; k++) {
System.out.println(ok + "=" + value[k]);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//HttpSession session = request.getSession();
}
}
then I can see the parameter output in the tomcat console..but I get the blank page..
It seems the page is stop after doGet method..
so how should I make it continue?
use that RequestDispatcher?
also how to handle in the doPost?
For your purpose, the best way would be to use a Filter.
Example :
#WebFilter(filterName = "monitoringFilter", urlPatterns = { "/*" })
public class MonitoringFilter implements Filter
{
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
// Right here do your stuff pretty much like in a servlet
request // ... get information you need
// Process request as normal
chain.doFilter(request,response);
}
#Override
public void init(FilterConfig config) throws ServletException
{
}
#Override
public void destroy()
{
}
}
More info :
Filter
You should use log4j and FileAppender to implement logging in your application.
Something like this :::
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class A{
static Log log = LogFactory.getLog(A.class);
void methodA(){
try{
log.info("I am inside A");
} catch(Exception e) {
log.error("error" , e);
}
}
}