The Student Room Group

Ajax call to servlet and JQeury not linking to HTML

Hi I am building a basic web app in html/css and jqeury all in seperate files. I am using tomcat 8 connection pooling. I have seperate file for creating connection pool and then calling that connection from each servlet I will be using. However, my jqeury is not linking up to my html. The full question is on https://stackoverflow.com/questions/54380950/ajax-call-to-servlet-and-jqeury-not-linking-to-html

and I would really appreciate it if someone could have a look.

Thanks
(edited 5 years ago)

Scroll to see replies

Are you seeing any HTTP error codes in the browser's console? (if you're using Chrome then you should get some decent diagnostic output from the F12 window)

Which HTTP error code does the AJAX request get back? is it returning a 404 (not found?) or a 500 (internal server error)? or a 401 (not authorised)? or a 400 (bad request)? or something else..?

Are you able to send a POST request to your API using a 3rd party tool such as Postman? -- this is a really neat tool for helping you develop and test your back-end web service by generating HTTP requests and seeing what happens:
https://www.getpostman.com/

The HTTP error code will be a big clue:
- 500 means that the javascript/AJAX is working fine and there's a bug in your Java code - no way to know how to fix that except with more logging, using the debugger, more exception handling, etc. .
- 401 means that you have some kind of authentication enabled (maybe Windows Auth or Oauth) and you're not sending the login credentials properly in the AJAX header
- 400 could be a bunch of things. I don't see anywhere that you're setting anything in your AJAX request for contentType="application/json" so that might be the problem -- https://stackoverflow.com/questions/4156991/jquery-ajax-returns-400-bad-request
- 404 could be that your AJAX URL is incorrect, or that the routing set up on your Java app is wrong. (Do you have any GET requests working in your app? e.g. for web pages or other content?)

To be honest, without first trying this using Postman and finding out what the actual HTTP error code is there's not really much else I can suggest.


---
Edit: This looks like it's going to cause problems in the AJAX code -- you need to JSON.stringify your data if you want to send it as JSON. i.e.:

var myData = {
method: method,
username: username,
pw: pw
};
var myJsonData = JSON.stringify(myData);


then in the AJAX request you'd want to specify this to ensure that the data is actually being sent in JSON format:

type: "POST",
contentType: "application/json",
data: myJsonData,


However, Java servlets appear to expecting data to be encoded using a default of x-www-form-urlencoding (which is fine for regular HTML forms, but nasty for AJAX), so if you change this to use application/json you'll need to handle it differently on the Java Servlet too: https://stackoverflow.com/questions/5338943/read-json-string-in-servlet
(edited 5 years ago)
Reply 2
When I press the login button on chrome nothing happens in the console but I get this error randomly:
GET http://localhost:8080/FYP/images/slider/p18.jpg 404
localhost/:247 GET http://localhost:8080/FYP/images/slider/p20.jpg 404
jquery.min.js:3 GET http://localhost:8080/FYP/fonts/glyphicons-halflings-regular.woff2 net::colone:RR_ABORTED 404
(anonymous) @ jquery.min.js:3
c @ jquery.min.js:3
fireWith @ jquery.min.js:3
ready @ jquery.min.js:3
H @ jquery.min.js:3
2(index):1 GET http://localhost:8080/FYP/fonts/glyphicons-halflings-regular.woff net::colone:RR_ABORTED 404

These may just be saying some pictures have not been referenced properly. I am not interested in that I will import all the pics later on I am concentrating on the function when user presses login the back end call is not being made.
(edited 5 years ago)
Those errors don't look related - 404 errors with JPG files (images) and .woff files (fonts), then it means that Tomcat hasn't got its MIME types configured to serve files with those extensions; it won't affect your AJAX request, but will probably affect the content you see -- your glyphicons/font-awesome icons won't show properly, and neither will your images. By default most file types are blocked on most web servers, except for the obvious ones (html, css, js, etc.)

- https://www.developershome.com/wap/wapServerSetup/tutorial.asp?page=settingUpMIME

For the AJAX issue it would probably still help to try hitting the endpoint with Postman to make sure the Java side is working OK.

Also, it looks like you aren't actually logging the errors being returned from the API -- there's just a comma after error and no event handler attached to it. You should be able to get better error logging output by changing your error handler a bit though : https://stackoverflow.com/a/1637051
(edited 5 years ago)
Reply 4
I made a mistake in the ajax function where error, function should be error: function. So the ajax call is now being made but it is not retrieving a success but rather an error meaning there is a problem connecting to the servlet right? This is the console log:

jquery.min.js:5 GET http://localhost:8080/FYP/errorpage.html 404
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:17
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
custom.js:35 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ,*…}
jquery.min.js:5 XHR failed loading: GET "http://localhost:8080/FYP/errorpage.html".
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:17
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
(edited 5 years ago)
Original post by HGrammer
I made a mistake in the ajax function where error, function should be error: function. So the ajax call is now being made but it is not retrieving a success but rather an error meaning there is a problem connecting to the servlet right?

Maybe - but what's the HTTP Status code (error code) being logged into the console? that will narrow it down - Tomcat might be receiving the request, and it might be reaching the servlet, but either of those could be rejecting it or throwing an error. the HTTP Status code will make it easier to know where to start.

if you can't see the HTTP status code in the console, then it might be in the Chrome devtools Network tab instead, in the status column.
Reply 6
Status code is 302:

Request URL: http://localhost:8080/FYP/LoginServlet
Request Method: POST
Status Code: 302
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Content-Type: text/plain
Date: Sat, 26 Jan 2019 19:43:17 GMT
Location: errorpage.html
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 29
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: JSESSIONID=1718F2C8BE3C15AC348392C030DE5781
Host: localhost:8080
Origin: http://localhost:8080
Referer: http://localhost:8080/FYP/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
X-Requested-With: XMLHttpRequest
method: personal
username:
pw:
Reply 7
Original post by HGrammer
Status code is 302:

Request URL: http://localhost:8080/FYP/LoginServlet
Request Method: POST
Status Code: 302
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Content-Type: text/plain
Date: Sat, 26 Jan 2019 19:43:17 GMT
Location: errorpage.html
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 29
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: JSESSIONID=1718F2C8BE3C15AC348392C030DE5781
Host: localhost:8080
Origin: http://localhost:8080
Referer: http://localhost:8080/FYP/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
X-Requested-With: XMLHttpRequest
method: personal
username:
pw:

I updated the servlet link in the ajax function to the full link as the servlet was in a src file so in ajax function url is /src/controller/LoginServlet. When I tested this the console log was:
jquery.min.js:5 POST http://localhost:8080/src/controller/LoginServlet 404
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:46
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
custom.js:64 Uncaught ReferenceError: data is not defined
at Object.error (custom.js:64)
at c (jquery.min.js:3)
at Object.fireWith [as rejectWith] (jquery.min.js:3)
at k (jquery.min.js:5)
at XMLHttpRequest.r (jquery.min.js:5)
error @ custom.js:64
c @ jquery.min.js:3
fireWith @ jquery.min.js:3
k @ jquery.min.js:5
r @ jquery.min.js:5
XMLHttpRequest.send (async)
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:46
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
jquery.min.js:5 XHR failed loading: POST "http://localhost:8080/src/controller/LoginServlet".
Original post by HGrammer
Status code is 302:

Request URL: http://localhost:8080/FYP/LoginServlet
Request Method: POST
Status Code: 302
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Content-Type: text/plain
Date: Sat, 26 Jan 2019 19:43:17 GMT
Location: errorpage.html
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 29
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: JSESSIONID=1718F2C8BE3C15AC348392C030DE5781
Host: localhost:8080
Origin: http://localhost:8080
Referer: http://localhost:8080/FYP/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
X-Requested-With: XMLHttpRequest
method: personal
username:
pw:


302 is a 'success' code which would normally cause the browser to redirect to whichever URL is at the 'Location', which is 'errorpage.html'

So the request is certainly reaching tomcat, but the server might be hiding the error? Do you have something set up in your tomcat configuration which is picking up the real status code and converting it into a 302 to errorpage.html? Worth checking the configuration to make sure that isn't happening so that you can see what the real error is.
(edited 5 years ago)
Original post by HGrammer
I updated the servlet link in the ajax function to the full link as the servlet was in a src file so in ajax function url is /src/controller/LoginServlet. When I tested this the console log was:
jquery.min.js:5 POST http://localhost:8080/src/controller/LoginServlet 404
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:46
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
custom.js:64 Uncaught ReferenceError: data is not defined
at Object.error (custom.js:64)
at c (jquery.min.js:3)
at Object.fireWith [as rejectWith] (jquery.min.js:3)
at k (jquery.min.js:5)
at XMLHttpRequest.r (jquery.min.js:5)
error @ custom.js:64
c @ jquery.min.js:3
fireWith @ jquery.min.js:3
k @ jquery.min.js:5
r @ jquery.min.js:5
XMLHttpRequest.send (async)
send @ jquery.min.js:5
ajax @ jquery.min.js:5
(anonymous) @ custom.js:46
dispatch @ jquery.min.js:3
v.handle @ jquery.min.js:3
jquery.min.js:5 XHR failed loading: POST "http://localhost:8080/src/controller/LoginServlet".


Whatever URL you had before seemed to be correct (it was reaching tomcat, and presumably you'd configured tomcat to host on http://localhost:8080/FYP ?) - The route you've specified using @WebServlet() is just "/LoginServlet" -- Java is compiled, so there are no source files, and there won't be a 'src/controller' folder in the compiled .java file.
(edited 5 years ago)
Reply 10
Original post by winterscoming
302 is a 'success' code which would normally cause the browser to redirect to whichever URL is at the 'Location', which is 'errorpage.html'

So the request is certainly reaching tomcat, but the server might be hiding the error? Do you have something set up in your tomcat configuration which is picking up the real status code and converting it into a 302 to errorpage.html? Worth checking the configuration to make sure that isn't happening so that you can see what the real error is.


https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call

if 302 is a success code and in my servlet I have put the errorpage link correctly, why is it showing up with an error in the console and not taking me to the new errorpage.html webpage?

In regards to tomcat server settings, I have never modified this and don't really know what to be looking at.
Original post by HGrammer
if 302 is a success code and in my servlet I have put the errorpage link correctly, why is it showing up with an error in the console and not taking me to the new errorpage.html webpage?

In regards to tomcat server settings, I have never modified this and don't really know what to be looking at.

Do you have a web.xml somewhere in your project? (maybe in a WEB-INF folder?) If so, does it have anything which looks like this?

<error-page>
<error-code>500</error-code>
<location>errorpage.html</location>
</error-page>



The reason the browser isn't redirecting is that the browser didn't send the request in the first place, instead the request has come from the JavaScript, so the browser won't handle the response either.
(edited 5 years ago)
Reply 12
Original post by winterscoming
Do you have a web.xml somewhere in your project? (maybe in a WEB-INF folder?) If so, does it have anything which looks like this?

<error-page>
<error-code>500</error-code>
<location>errorpage.html</location>
</error-page>



The reason the browser isn't redirecting is that the browser didn't send the request in the first place, instead the request has come from the JavaScript, so the browser won't handle the response either.

I have web.xml in web-inf folder but the error page code you posted above is not in the web.xml file.

Also you said the browser didn't send the initial request javascript did so whatever the response is the browser wont display it as it didnt send the response. That sounds a tad confusing, how can I correct this then?
Original post by HGrammer
I have web.xml in web-inf folder but the error page code you posted above is not in the web.xml file.

Also you said the browser didn't send the initial request javascript did so whatever the response is the browser wont display it as it didnt send the response. That sounds a tad confusing, how can I correct this then?

Are there any error codes in the web.xml file at all though? e.g. 400, 401, 404, etc.

The error codes could be any number in the range 400-599, but you won't know which until you take all of them out and get rid of the redirect altogether - once you find the real error it should be easier to debug it properly.


What I mean by the browser not sending the request is that it's the browser's built-in JavaScript scripting engine sending the request rather than the main web browser itself - when the scripting engine gets the response, it's entirely up to your code in terms of what it's actually doing.

The thing is that you don't want to handle it at all, you need it gone because a generic "errorpage.html" isn't going to help you actually debug the error. (You could put it back later after you've fixed the problem, but this sort of thing isn't helpful when writing code)
(edited 5 years ago)
Reply 14
Original post by winterscoming
Are there any error codes in the web.xml file at all though? e.g. 400, 401, 404, etc.

The error codes could be any number in the range 400-599, but you won't know which until you take all of them out and get rid of the redirect altogether - once you find the real error it should be easier to debug it properly.


What I mean by the browser not sending the request is that it's the browser's built-in JavaScript scripting engine sending the request rather than the main web browser itself - when the scripting engine gets the response, it's entirely up to your code in terms of what it's actually doing.

The thing is that you don't want to handle it at all, you need it gone because a generic "errorpage.html" isn't going to help you actually debug the error. (You could put it back later after you've fixed the problem, but this sort of thing isn't helpful when writing code)


There are no error codes at all in the web.xml file under web-inf. In regards to everything else you said, I somewhat understand it but I’m new to web development in Java. Although I have done java programming before, I’m still quite new to this.

I’m just trying to run a simple banking app. I’ve got my index.html file linked to a JS file with an ajax function linked to a LoginServlet. This then redirect the webpage to another html webpage such as errorpage.

Atm the problem is the ajax code not linking to the servlet/servlet not linking to error page. I’ve followed so many tutorials it’s as though something just isn’t clicking for me.
Original post by HGrammer
There are no error codes at all in the web.xml file under web-inf. In regards to everything else you said, I somewhat understand it but I’m new to web development in Java. Although I have done java programming before, I’m still quite new to this.

I’m just trying to run a simple banking app. I’ve got my index.html file linked to a JS file with an ajax function linked to a LoginServlet. This then redirect the webpage to another html webpage such as errorpage.

Atm the problem is the ajax code not linking to the servlet/servlet not linking to error page. I’ve followed so many tutorials it’s as though something just isn’t clicking for me.

Web development with java is definitely a lot more complex than just building a plain Java forms app - there are a lot more moving parts for handling the HTTP requests and responses between the browser and the servlet (particularly around the tomcat 'container' which runs the servlet).
There's some good background reading here to help understand what's actually happening with HTTP requests and the tomcat containers, although this page is from 2002 so don't look at the code here as a good example of how to do things because that'll be misleading: https://www.developer.com/java/ent/article.php/2178651/Understanding-Servlets.htm


I can't see anything in the LoginServlet which is redirecting to errorpage.html - is that something you've added? If not, then it suggests to me that tomcat is handling an error and swallowing it up, which makes it hard to find out what the 'real' error is. The redirects I can see in the servlet seem to be for cus_profile.jsp and bus_profile.jsp instead.

If this is happening, then it could be a combination of many things and the best thing to do is to cut out some of the noise and try to rule out different problems - the first thing is to make sure that tomcat isn't doing anything like swallowing real errors - there's 2 different ways you could do that:

One way would be to try using plain HTML to send your login data like this and let the browser send the POST request instead - that way the browser will also handle the 302 redirect

<form action="LoginServlet" method="post">
Method: <br/> <input type="text" name="method"> <br/>
Username: <br/> <input type="text" name="username"> <br/>
Password: <br/> <input type="password" name="pw"> <br/>
<input type="submit" value="login">
</form>

If you do this, then you'll probably go back to the 404 error ("Not found") for errorpage.html that you had earlier - which might just be that there's no errorpage.html in your WebContent folder?


The other way would be to try this out using Postman, which I definitely recommend using so that you can test your servlet on its own - https://www.getpostman.com/


If the above both work then that rules out problems with either tomcat or the servlet
(edited 5 years ago)
Reply 16
Original post by winterscoming
Web development with java is definitely a lot more complex than just building a plain Java forms app - there are a lot more moving parts for handling the HTTP requests and responses between the browser and the servlet (particularly around the tomcat 'container' which runs the servlet).
There's some good background reading here to help understand what's actually happening with HTTP requests and the tomcat containers, although this page is from 2002 so don't look at the code here as a good example of how to do things because that'll be misleading: https://www.developer.com/java/ent/article.php/2178651/Understanding-Servlets.htm


I can't see anything in the LoginServlet which is redirecting to errorpage.html - is that something you've added? If not, then it suggests to me that tomcat is handling an error and swallowing it up, which makes it hard to find out what the 'real' error is. The redirects I can see in the servlet seem to be for cus_profile.jsp and bus_profile.jsp instead.

If this is happening, then it could be a combination of many things and the best thing to do is to cut out some of the noise and try to rule out different problems - the first thing is to make sure that tomcat isn't doing anything like swallowing real errors - there's 2 different ways you could do that:

One way would be to try using plain HTML to send your login data like this and let the browser send the POST request instead - that way the browser will also handle the 302 redirect

<form action="LoginServlet" method="post">
Method: <br/> <input type="text" name="method"> <br/>
Username: <br/> <input type="text" name="username"> <br/>
Password: <br/> <input type="password" name="pw"> <br/>
<input type="submit" value="login">
</form>

If you do this, then you'll probably go back to the 404 error ("Not found") for errorpage.html that you had earlier - which might just be that there's no errorpage.html in your WebContent folder?


The other way would be to try this out using Postman, which I definitely recommend using so that you can test your servlet on its own - https://www.getpostman.com/


If the above both work then that rules out problems with either tomcat or the servlet


I will try this in a few hours and get back to you. In the mean time do you know anything about JNDI?
I wa wondering Can I seperate the app logic in multiple servlets eg one for login controller one for accounts controller etc and how would this affect my connection pooling?

I have seen tutorials where the init method to initialise context and env context to get jdni datasource is at the beginning of a servlet. But what about if i have multiple servlets, do they all do the init method? If so that seems repetitive is there no way to abstract it and call a connection from a datasource from any servlet within the same project?
Original post by HGrammer
I will try this in a few hours and get back to you. In the mean time do you know anything about JNDI?
I wa wondering Can I seperate the app logic in multiple servlets eg one for login controller one for accounts controller etc and how would this affect my connection pooling?

I have seen tutorials where the init method to initialise context and env context to get jdni datasource is at the beginning of a servlet. But what about if i have multiple servlets, do they all do the init method? If so that seems repetitive is there no way to abstract it and call a connection from a datasource from any servlet within the same project?


I'm not too familiar with JNDI to be honest, but there's nothing special about Servlet Controller classes to prevent you from creating the Datasource in another shared class. Also no reason why you need to have any database connection code in the Servlet Controller either.

It sounds like the examples you've seen are showing a few bad 'habits' putting database logic inside a Servlet controller rather than separating them out (to avoid copy-paste repetition, also separation of concerns - the Servlet Controllers are already doing enough by handling the HTTP request/responses/errors without having to care about database connections too.

You could move all the datasource/connection/database logic verbatim from the LoginServlet into another class, basically following the repository pattern -- https://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/. This way, the same Database can be reused in multiple servlets, for example, an AccountRepository which is used by the LoginServlet and the AccountsServlet and maybe others.

Using the repository pattern means you'd put database queries there too so they would have classes like this which encapsulate anything to do with data sources or connections:

public class AccountRepository {
public ArrayList<Account> getAll() { /* ... */ }
public Account getAccount(int accountNumber) { /* ... */ }
public int createAccount(Account newAccount) { /* ... */ }
public Account updateAccount(Account updatedAccount) { /* ... */ }
public void deleteAccount(int accountNumber) { /* ... */ }
}

Also, if you ended up splitting your repositories up for different kinds of objects (e.g. one for Accounts, one for Customers, etc.), you might even have a 'BaseRepository' which has the common logic for creating a DataSource, then derive AccountRepository and CustomerRepository classes from that.

There's always ways to split logic away from servlets anyway - hopefully it means that your Servlets will have much simpler methods like this instead:

public class AccountsServlet extends HttpServlet {
private static final AccountRepository accountRepository = new AccountRepository();
private static final CustomerRepository customerRepository = new CustomerRepository();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO -- do something with accountRepository and/or customerRepository
}
}
(edited 5 years ago)
Reply 18
Original post by winterscoming
I'm not too familiar with JNDI to be honest, but there's nothing special about Servlet Controller classes to prevent you from creating the Datasource in another shared class. Also no reason why you need to have any database connection code in the Servlet Controller either.

It sounds like the examples you've seen are showing a few bad 'habits' putting database logic inside a Servlet controller rather than separating them out (to avoid copy-paste repetition, also separation of concerns - the Servlet Controllers are already doing enough by handling the HTTP request/responses/errors without having to care about database connections too.

You could move all the datasource/connection/database logic verbatim from the LoginServlet into another class, basically following the repository pattern -- https://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/. This way, the same Database can be reused in multiple servlets, for example, an AccountRepository which is used by the LoginServlet and the AccountsServlet and maybe others.

Using the repository pattern means you'd put database queries there too so they would have classes like this which encapsulate anything to do with data sources or connections:

public class AccountRepository {
public ArrayList<Account> getAll() { /* ... */ }
public Account getAccount(int accountNumber) { /* ... */ }
public int createAccount(Account newAccount) { /* ... */ }
public Account updateAccount(Account updatedAccount) { /* ... */ }
public void deleteAccount(int accountNumber) { /* ... */ }
}

Also, if you ended up splitting your repositories up for different kinds of objects (e.g. one for Accounts, one for Customers, etc.), you might even have a 'BaseRepository' which has the common logic for creating a DataSource, then derive AccountRepository and CustomerRepository classes from that.

There's always ways to split logic away from servlets anyway - hopefully it means that your Servlets will have much simpler methods like this instead:

public class AccountsServlet extends HttpServlet {
private static final AccountRepository accountRepository = new AccountRepository();
private static final CustomerRepository customerRepository = new CustomerRepository();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO -- do something with accountRepository and/or customerRepository
}
}




Original post by winterscoming
I'm not too familiar with JNDI to be honest, but there's nothing special about Servlet Controller classes to prevent you from creating the Datasource in another shared class. Also no reason why you need to have any database connection code in the Servlet Controller either.

It sounds like the examples you've seen are showing a few bad 'habits' putting database logic inside a Servlet controller rather than separating them out (to avoid copy-paste repetition, also separation of concerns - the Servlet Controllers are already doing enough by handling the HTTP request/responses/errors without having to care about database connections too.

You could move all the datasource/connection/database logic verbatim from the LoginServlet into another class, basically following the repository pattern -- https://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/. This way, the same Database can be reused in multiple servlets, for example, an AccountRepository which is used by the LoginServlet and the AccountsServlet and maybe others.

Using the repository pattern means you'd put database queries there too so they would have classes like this which encapsulate anything to do with data sources or connections:

public class AccountRepository {
public ArrayList<Account> getAll() { /* ... */ }
public Account getAccount(int accountNumber) { /* ... */ }
public int createAccount(Account newAccount) { /* ... */ }
public Account updateAccount(Account updatedAccount) { /* ... */ }
public void deleteAccount(int accountNumber) { /* ... */ }
}

Also, if you ended up splitting your repositories up for different kinds of objects (e.g. one for Accounts, one for Customers, etc.), you might even have a 'BaseRepository' which has the common logic for creating a DataSource, then derive AccountRepository and CustomerRepository classes from that.

There's always ways to split logic away from servlets anyway - hopefully it means that your Servlets will have much simpler methods like this instead:

public class AccountsServlet extends HttpServlet {
private static final AccountRepository accountRepository = new AccountRepository();
private static final CustomerRepository customerRepository = new CustomerRepository();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO -- do something with accountRepository and/or customerRepository
}
}


I read the link and I didn’t really understand it so I started researching What is repo pattern and dao v repo but just got confused even more. Would you be able to explain it in the context of my application?
I wasn’t really going to follow a method but thinking about it, it resembled the dao pattern.

I was basically going to have js ajax call (with a parameter METHOD) to login servlet which reads query and has cases eg

Case:
Method 1 // someMethod(“”)
Method 2 // “”

Inside the method, an object would be created eg an acc obj containing name bal acc no etc. a seperate java class accObj will have the aforementioned fields. In this method (called by case in loginservlet) will contain the dbconnection save relavant parameters in accObj fields and return to the servlet only the requested fields.

What do you suggest?
Original post by HGrammer
I read the link and I didn’t really understand it so I started researching What is repo pattern and dao v repo but just got confused even more. Would you be able to explain it in the context of my application?
I wasn’t really going to follow a method but thinking about it, it resembled the dao pattern.
Don't worry about the difference between 'DAO' vs 'Repository' (those patterns are similar to each other anyway) - The repository and DAO patterns are both about putting Create/Read/Update/Delete (CRUD) database logic into its own class(es), so if you have a really simple database and simple queries then they pretty much end up being exactly the same thing, and that's OK. So if you were going to do something like that already then that's fine.

The only difference between DAO and Repository is where you might have some bigger, more complex objects in your program. For example, you could have tables called 'Customer' and 'Order' where a customer has many orders.

DAO Pattern - A Customer DAO and an Order DAO which only interact with single tables, and Java would perform separate queries to read Customers and Objects separately.

Repository pattern - A Customer Repository which queries a Customer object that also includes a list of orders using a SQL Join and object mapping, getting all the data back in just one query. A Repository will do more work to make sense of the database by joining tables together and pulling back complex objects.


Original post by HGrammer

I was basically going to have js ajax call (with a parameter METHOD) to login servlet which reads query and has cases eg

Case:
Method 1 // someMethod(“”)
Method 2 // “”

Inside the method, an object would be created eg an acc obj containing name bal acc no etc. a seperate java class accObj will have the aforementioned fields. In this method (called by case in loginservlet) will contain the dbconnection save relavant parameters in accObj fields and return to the servlet only the requested fields.

What do you suggest?
Did you have any luck testing the servlet using the HTML <form> code I pasted earlier, and are you sure you actually need AJAX to do this? Maybe i'm misunderstanding, but from what you've said in the last few posts it sounds like a form would be able to do the same thing (sending data from some <input> fields), without any JavaScript.
(edited 5 years ago)

Quick Reply

Latest

Trending

Trending