Spring Hibernate, updating JSP view while selecting from dropdown menu - java

my controller:
public String showWeather(Model model) {
model.addAttribute("weather", weatherService.listCities());
return "weather";
}
my weather.jsp
<select class="data">
<c:forEach items="${weather}" var="city">
<option>${city.name}</option>
</c:forEach>
</select>
How can I make that everytime I highlight/select something from the dropdown menu, new info would be displayd next to it from database according to the City?
First of all, must I send all data from database to my JSP with controller at first, or can data be transfered from database to JSP meanwhile I highlight/select items on the list(so when I select city "A", then the query will get all information about city "A" and I can use the info)?
here are my tables:
CITIES(id serial, name varchar(40))
WEATHER(id serial, city_id int, temp int, data date)
So basically I have list of CITIES in my dropdown menu, and when city is selected, then the WEATHER with that city_id will be queried from database in theory.
If the live updating is not possible, how should I do it otherways?
Feel free to ask questions or give suggestions.

I think you should use AJAX in this case
use JQUERY on change event whick will send your cityId to SpringMVC controller, as the response your controller should return wheather, and then update your GUI component with this result:
then main difference is that your controller should return anything but the view. You can do it using #ResponseBody annotation:
for example this controller will return you temperature as String when you request
it for city with id=222
/getTemperature/222
#RequestMapping(value="/getTemperature/{id}", method=RequestMethod.GET)
#ResponseBody
public String getTemparature(#PathVariable("id") Integer id){
String weather = someDaoObect.getTemperature(id);
return weather;
}
in this case that code behaves exactly like Servlet where you write your result in HttpServletResponse.
Hope it will help you.

What are you talking about it is exactly what Ajax is focused on (see Ajax Programming), bring data between the server and client (browser), sending and retrieving data asynchronously. In your case, when the user selects and item the application must go and query to the server what is needed to do it (update information in the db, return something to the browser, etc).
In your case, I don't know if you can include a new library and use it, but there are so many to use within a web project in Java, and are so easy to integrate and use it:
AjaxTags JavaScript-JSP Library - http://ajaxtags.sourceforge.net/
AjaxAnywhere - http://ajaxanywhere.sourceforge.net
jMaki - http://ajax.java.net/
Also you can include one of the beautiful JavaScript libraries (ex: jQuery, Prototype, Ext, Dojo, etc) that provides same functionality to send and receive information asynchronously between the browser and the server.

Related

NoSQL injection - java server

I am trying to create a java servlet with a NoSQL injection vulnerability. I've connected the servlet with MongoDB and check if the login info submitted by the user exists, I'm doing the next query:
String andQuery = "{$and: [{user: \""+u+"\"}, {password: \""+p+"\"}]}";
Where u is the user and p is the password given by the user.
For what I've seen this is correct, and the NoSQL injection should exist, bu I really dont kno how to prove it.
I've tried submitting with burp this:
username[$ne]=1&password[$ne]=1
But its not working, and when I check the content of u and p after I submitted that the content of both variables is null.
I dont have the servlet configured to receive json objects so I need a solition that doesn't imply send a json object with burp.
PD: I tryed also to insert something like this:
{\"$gt\":\"\" }
in the user and password fields but the result query is
{"$and": [{"user": "{\"$gt\":\"\" }"}, {"password": "{\"$gt\":\"\" }"}]}
I guess this doesn't work because the {"$gt":"" } is in quotes, ¿how can I do the servlet to be vulnarable and with which input it would be vulnerabel?

How to retrieve an integer URL parameter with JSP? [duplicate]

In JSP how do I get parameters from the URL?
For example I have a URL www.somesite.com/Transaction_List.jsp?accountID=5
I want to get the 5.
Is there a request.getAttribute( "accountID" ) like there is for sessions or something similar?
About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
The interesting parts are in bold :)
So, to answer your question, you should be able to access it like this (using EL):
${param.accountID}
Or, using JSP Scriptlets (not recommended):
<%
String accountId = request.getParameter("accountID");
%>
In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.
This example demonstrates how to include the value of a request parameter in the generated output:
Hello <b><%= request.getParameter("name") %></b>!
If the page was accessed with the URL:
http://hostname.com/mywebapp/mypage.jsp?name=John+Smith
the resulting output would be:
Hello <b>John Smith</b>!
If name is not specified on the query string, the output would be:
Hello <b>null</b>!
This example uses the value of a query parameter in a scriptlet:
<%
if (request.getParameter("name") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request. getParameter("name")+"</b>!");
}
%>
Use EL (JSP Expression Language):
${param.accountID}
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.
String accountID = request.getParameter("accountID");
www.somesite.com/Transaction_List.jsp?accountID=5
For this URL there is a method call request.getParameter in java , if you want a number here cast into int, similarly for string value cast into string. so for your requirement , just copy past below line in page,
int accountId =(int)request.getParameter("accountID");
you can now call this value useing accountId in whole page.
here accountId is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET method if you hit POST request then their will be an error.
Hope this is helpful.
example you wanted to delete the subject record with its subject_id
#RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int subjectid) {
subjectsDao.delete(subjectid);
return new ModelAndView("redirect:/subject_setup");
}
and the parameter will be used for input on your query
public int delete(int subjectid) {
String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
return template.update(sql);
}
page 1 :
Detail
page 2 :
<% String id = request.getParameter("userid");%>
// now you can using id for sql query of hsql detail product

to pass the value retrieved from a database to the be used in other subsequent forms

I am doing a project with the help of java,servlets and tomcat apache. First i have created a form for user login(1st form), upon submitting this, we are asked to input a phone number(2nd form) . This number i have retrieved using getParameter in the third form. But again after submitting the 3rd form,i need the phone number to be displayed in the fourth form(which is generated upon submitting the 3rd form). i tried using input tag with hidden attribute , but when i passed its value as request.getParameter, its displaying request.getParameter but not the number. Hw can i do it. I am not using jsp. I want to do directly with java and servlet.
Welcome to the Java Web Development.
I think you are in need to learn of Session and Session Handling in java web applications.
In the 3rd form when you retrieve the phoneNumber store it in a session object as:
HttpSession session = request.getSession();
session.setAttribute("phone", phoneNumber); // pair of String=key and Object=value
Now in 4th form you can get the phone number as:
Object phoneNumber = request.getSession().getAttribute("phone");
session.invalidate(); //clear-up current session
Parse this phoneNumber in whatever form you want.

Configuring server side Datatables for an unknown number of tables

I am using DataTables with the tables being generated in a java controller class that talks to the database. Given a category id, the controller class returns an unknown number of preformatted HTML tables, one for each section in the given category queried. Ideally I would like to display each table as a DataTable on the same page, but unsure if that's possible given that I don't know how many tables I will be getting back so I can't set up their behavior before the query.
Is there a way to format the tables when/as I get them from the controller? I attempted to prepend each table with its own .ready block but that didn't seem to do the trick though I'm fairly new to jQuery and could just be missing something. I used the barest of configuration to try to get it working first
$(document).ready(function(){
$("#results").dataTable({
"bJQueryUI" : true
});
});
$(document).ready(function() {
$('.dataTable').dataTable();
} );
Turns out to work after all, but ONLY if you specify the tables as class="dataTable" which isn't well documented or explained, hopefully this un-confuses someone else!

How to store all user activites in a website..?

I have a web application build in Django + Python that interact with web services (written in JAVA).
Now all the database management part is done by web-services i.e. all CRUD operations to actual database is done by web-services.
Now i have to track all User Activities done on my website in some log table.
Like If User posted a new article, then a new row is created into Articles table by web-services and side by side, i need to add a new row into log table , something like "User : Raman has posted a new article (with ID, title etc)"
I have to do this for all Objects in my database like "Article", "Media", "Comments" etc
Note : I am using PostgreSQL
So what is the best way to achieve this..?? (Should I do it in PostgreSQL OR JAVA ..??..And How..??)
So, you have UI <-> Web Services <-> DB
Since the web services talk to the DB, and the web services contain the business logic (i.e. I guess you validate stuff there, create your queries and execute them), then the best place to 'log' activities is in the services themselves.
IMO, logging PostgreSQL transactions is a different thing. It's not the same as logging 'user activities' anymore.
EDIT: This still means you create DB schema for 'logs' and write them to DB.
Second EDIT: Catching log worthy events in the UI and then logging them from there might not be the best idea either. You will have to rewrite logging if you ever decide to replace the UI, or for example, write an alternate UI for, say mobile devices, or something else.
For an audit table within the DB itself, have a look at the PL/pgSQL Trigger Audit Example
This logs every INSERT, UPDATE, DELETE into another table.
In your log table you can have various columns, including:
user_id (the user that did the action)
activity_type (the type of activity, such as view or commented_on)
object_id (the actual object that it concerns, such as the Article or Media)
object_type (the type of object; this can be used later, in combination with object_id to lookup the object in the database)
This way, you can keep track of all actions the users do. You'd need to update this table whenever something happens that you wish to track.
Whenever we had to do this, we overrode signals for every model and possible action.
https://docs.djangoproject.com/en/dev/topics/signals/
You can have the signal do whatever you want, from injecting some HTML into the page, to making an entry in the database. They're an excellent tool to learn to use.
I used django-audit-log and I am very satisfied.
Django-audit-log can track multiple models each in it's own additional table. All of these tables are pretty unified, so it should be fairly straightforward to create a SQL view that shows data for all models.
Here is what I've done to track a single model ("Pauza"):
class Pauza(models.Model):
started = models.TimeField(null=True, blank=False)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
audit_log = AuditLog()
If you want changes to show in Django Admin, you can create an unmanaged model (but this is by no means required):
class PauzaAction(models.Model):
started = models.TimeField(null=True, blank=True)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
# fields added by Audit Trail:
action_id = models.PositiveIntegerField(primary_key=True, default=1, blank=True)
action_user = models.ForeignKey(User, null=True, blank=True)
action_date = models.DateTimeField(null=True, blank=True)
action_type = models.CharField(max_length=31, choices=(('I', 'create'), ('U', 'update'), ('D', 'delete'),), null=True, blank=True)
pauza = models.ForeignKey(Pauza, db_column='id', on_delete=models.DO_NOTHING, default=0, null=True, blank=True)
class Meta:
db_table = 'testapp_pauzaauditlogentry'
managed = False
app_label = 'testapp'
Table testapp_pauzaauditlogentry is automatically created by django-audit-log, this merely creates a model for displaying data from it.
It may be a good idea to throw in some rude tamper protection:
class PauzaAction(models.Model):
# ... all like above, plus:
def save(self, *args, **kwargs):
raise Exception('Permission Denied')
def delete(self, *args, **kwargs):
raise Exception('Permission Denied')
As I said, I imagine you could create a SQL view with the four action_ fields and an additional 'action_model' field that could contain varchar references to model itself (maybe just the original table name).

Categories

Resources