I referred to Java MVC, and I understood the following.(please correct me if I'm wrong)
M->Model(It is a Java Bean)
V->View(JSP/HTML)
C->Controller(Servlet)
Here when going through Java Beans in JDBC there are getters and setters, I want to know if this is all the columns from my DB, for example, I've 10 Columns, Do I need to do a Getters and Setters for all the 10 Columns?
Should I write my JDBC code in Servlet or Bean?
In my JSP I've two textboxes that fetch data from Database Columns. for that I use to do something like below (Just for Demonstration sake).
`
<table>
<tr>
<td>
<input type="text" value="<%=i%>" name="id1" id="id1">
</td>
<td>
<center>
<input type="text" value="<%=rs.getString("DBID")%>" readonly="readonly" id="abc<%=i%>" name="abc<%=i%>" size="100">
</center>
</td>
<td>
<input type="text" value="<%=i%>" name="id2" id="id2">
</td>
<td>
<center>
<input type="text" value="<%=rs.getString("description")%>" readonly="readonly" id="ab<%=i%>" name="ab<%=i%>" size="100">
</center>
</td>
</tr>
</table>
`
Here I'm fetching content from database and putting it in 2 textboxes.
How can I do it using MVC approach?
1.Here when going through Java Beans in JDBC there are getters and setters, I want to know if this is all the columns from my DB, for example, I've 10 Columns, Do I need to do a Getters and Setters for all the 10 Columns?
Yes you need 10 properties with the getter and setter.
2.Should I write my JDBC code in Servlet or Bean?
The JDBC code should be in a service which is called from the controller or in the controller itself.
3.In my JSP I've two textboxes that fetch data from Database Columns. for that i use to do something like below(Just for Demonstration sake).
You have to call the getter of the bean for the property you need.
You can find good tutorials in the web.
Please do more study to understand for e.g. http://howtodoinjava.com/2015/02/05/spring-mvc-hello-world-example/
But i ll try to answer ur questions
1) Here when going through Java Beans in JDBC there are getters and setters, I want to know if this is all the columns from my DB, for example, I've 10 Columns, Do I need to do a Getters and Setters for all the 10 Columns?
-> A Java bean need not have "all" the columns, instead bean should reflect truly which fields (whether columns in DB tables or computed ones) are required at the "view" (or calling business logic).
2) Should I write my JDBC code in Servlet or Bean?
-> JDBC code can be put into a separate LAYER - read more about DAO and layered architectures. So a single controller class receives an event (request) and then call the appropriate "manager" class which know what bunisess action is requried. It can call other manager classes which intern can call DB layer (DAO will help here)
for e.g. suppose controller receives request to create Order -->
Controller.invoke(Request reqCreateOrder) --> CreateOrderHandler.execute(OrderBean ob) ---> OrderDao.create(OrderVO) ---> [insert query]
3) In my JSP I've two textboxes that fetch data from Database Columns. for that i use to do something like below(Just for Demonstration sake).
--> similarly for fetch as well
Controller.invoke(Request reqFetchOrder)
--> FetchOrderHandler.execute(OrderBean bean) ---> OrderDao.fetch(OrderBean bean) ---> [select query]
--> FetchOrderView.render(OrderVO bean) --> invokes JSP !!
MVC is just a paradygm. In real world you may have much more layers :
view (JSP) (the less possible scriptlet here)
front-controller (provided by a framework such as Spring MVC or Struts)
controller (provided by programmer) : processes request parameters, call next layer and forwards to a view
service : implementation of business rules <= here should be the intelligence
persistence (JDBC will come here, but you could have ORM such as Hibernate or JPA)
Object model (beans) go through all those layers.
It would be too long for a SO answer to explain all that so :
search on google and wikipedia for MVC and MVC2 patterns
read tutorials (Struts, Spring, Hibernate ...)
discuss with fellows that already used them => not to be done in SO
choose an architecture with or without framework (*)
try it and than ask precise question here if needed
(*) Even without framework try to separate view (JSP) - controller (servlet) - service - persistence
Related
So I have a .jsp page which has a form on it, like this (naturally this is a massive simplification):
<form:form commandName="myCommand" method="post">
<form:select path="values" class="select-tall" multiple="multiple" id="mySelect">
<option>first</option>
<option>second</option>
<option>third</option>
</form:select>
<button type="submit" class="button">Save</button>
</form:form>
When the submit button is pressed, the form is submitted(somehow) and the path= attributes are used to bind the data inside the form elements to the properties of an instance of a plain old java object. I understand how this POJO is specified, and I understand how the POST request is routed to the correct controller, but I don't understand where or how the form values are mapped to the given POJO.
What I don't understand is:
How does the spring tag library modify the form such that this binding takes place?
How would one go about doing this in a manual or ad-hoc fashion(using a Javascript onSubmit() method, say)?
Essentially my question is: How does the spring-form.tld tag library work?
Any resources, or even a high-level explanation in your own words, would be extremely helpful.
I've implemented a work-around solution in the mean time (dynamically adding items to a hidden form element), but I feel like this is hack-y and the wrong solution.
I have been using JSTL to fetch values from my database and display it in my jsp page using a similar code as shown below.
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb"
user="root" password="secret"
/>
<sql:query var="list_users" dataSource="${myDS}">
SELECT * FROM users;
</sql:query>
<c:forEach var="user" items="${listUsers.rows}">
<c:out value="${user.name}" />
<c:out value="${user.email}" />
<c:out value="${user.profession}" />
</c:forEach>
My team leader advised me that it is not a good practice to put queries in the jsp page directly. Since there is a database name and username and password in this code I'm not sure if this code implements proper security. I would like to know your thoughts on the matter, and if there is any alternative to do this using JSTL itself.
Since JSTL is executed on server side, there's no security hole because the query cannot be seen by clients of the application. There are other problems with this approach:
The query is not reusable. If you need it in other pages, you will need to repeat the query. When you have simple queries like this one you cannot check the problem, but this arises with more complex statements that needs parameters as well.
You're creating a connection manually per page! This will slow your application. Use a proper datasource for a database connection pool configured as a resource or programatically (C3PO or BoneCP, for example)
Move all your database code into proper Data Access Layer classes. And use <sql> for JSTL for learning purposes only, not for real world applications.
More info:
How to use JSTL sql tag
Retrieve values from JDBC and use JSTL tags to call the methods
Should a database connection stay open all the time or only be opened when needed?
You should really do your query in your java class, not in the jsp, like your team leader advised.
On the security side it doesn't really matter, all the code is available on the server, jsp or java. The sql tag shouldn't output that information in the generated page.
But really the question is more about the right use of the technologies:
jsp is used as a template, it should take data and show them to the end user. Some basic operation can be done life looping on data list or formating data, but this should be only specific to the view you want to make
java controler is used to recuperate data and configure the view as needed like which jsp to use and which data to send in that jsp
I m having a hard time working with array inputs for example how can I:
Write the following html input using spring form tag:
<input name="phone []"/>
<input name="phone[]"/>
I tried
<form:input path="phone []"/>
but no luck throws error saying that class attribute phone [] does not exists.
2 . After you tell me how to do step 1 how can i repopulate the form with user inputs values using #ModelAttribute In case of validation error. Obviously normal using of <spring:input path="phone"/> won't work cause phone has a list of values.
By the way I use controller with annotations.
Thanks
This depends if you are trying to do dynamic forms or just a static list based forms. For static ones - you need to iterate manually:
<c:forEach items="myModel.phones" varStatus="status">
<form:input path="phones[${status.index}]" />
</c:forEach>
Dynamic forms are a little bit complicated and you should try google as this was asked and answered few times.
I'm implementing a JSP which expects a few parameters which have to be validated before running the jsp.
Suggestion: Validate the parameters inside the JSP using
Taglibraries
Suggestion: Pre-parse the Parameters in a Filter
What do you think?
Edit
Thank you for the good answers, but I was wondering what would be the best practice in case you are offering a service like google chart API where you can't expect that the parameters are checked by a form before they are sent.
example:
https://chart.googleapis.com/chart?cht=&chd=&chs=&...additional_parameters...
None of both are good approaches. Controller/business logic doesn't belong in a JSP (tag). A filter is almost good, but it's not specific enough. This job should be done by a servlet. You're submitting the form to a servlet to postprocess it, right? It sounds like that you're not already doing that, the answer would otherwise have been pretty straightforward.
In our servlets tag wiki page you can find a hello world example of a good approach of using a JSP with a Servlet to postprocess a form submit. Here's an extract of relevance:
<input id="name" name="name" value="${fn:escapeXml(param.name)}">
<span class="error">${messages.name}</span>
with
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
}
// ...
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
Further, there exist MVC frameworks which removes all the boilerplate (duplicated/repeated) servlet code for this kind of use cases, such as JSF, Spring MVC, Wicket, Stripes, Struts2, etc. With for example JSF it look just something like this:
<h:inputText id="name" value="#{bean.name}" required="true" requiredMessage="Please enter name" />
<h:message for="name" />
That's all. The JSF's FacesServlet controller servlet will validate if it's been filled in and display a (configureable) message at the given location, without any need for custom Java code. You could even move it to the model, JSF has transparent support for JSR303 bean validation as well. E.g.
<h:inputText id="name" value="#{bean.name}" />
<h:message for="name" />
with
#NotNull(message="Please enter name")
private String name;
Update as per your edit:
Thank you for the good answers, but I was wondering what would be the best practice in case you are offering a service like google chart API where you can't expect that the parameters are checked by a form before they are sent. example: https://chart.googleapis.com/chart?cht=&chd=&chs=&...additional_parameters...
Just use a servlet the same way. The only difference is that you've to implement the job in doGet() instead of doPost() and if necessary return HTTP 400 on an error :) Once again, check our servlets tag wiki page to understand their purpose better. Or to go a step further, use a webservice framework instead, such as JAX-WS or JAX-RS which do this job transparently like a MVC framework does for HTML pages.
Use an MVC Framework (Spring MVC, Stripes, Struts 2 etc.) and validate the parameters in the controller class. Every MVC framework supports parameter validation, and you get a clean separation of concerns.
Example: Spring MVC automatically registers JSR-303-style parameter Validation (if you have a JSR-303 provider, e.g. Hibernate-Validator, on the classpath) when using mvc:annotation-driven
I have a spring MVC application using JSP as my view technologies with Jquery for AJAX. I have a table such as the following:
<table>
<tr>
<td>name1</td>
<td>value1</td>
<td>setting1</td>
</tr>
<tr>
<td>name2</td>
<td>value2</td>
<td>setting2</td>
</tr>
</table>
I need to serialize this table so that it can later be bound to an object in my controller. However the jquery serialize() method only works on form fields. What would be the best approach to get the table data into the HTTP request so that I can later bind it to a java object?
EDIT:
I have a java object that has a collection so
class MyOject {
private List<AnotherObject> items = new ArrayList<AnotherObject>();
// standard getters and setters
}
class AnotherObject {
private name;
private value;
private setting;
// getters and setters
}
In the screen the user is creating new items on the fly. When the user is done, they submit the form and then I need to process all the items in the list and instantiate a new collection with those items.
For display purposes I am creating a new table row when an item is created.
The <Form> tag is how you tell the browser "Put this stuff in the web request." That's how you get object binding in Spring. What is your reason for not using a Form? You don't necessarily have to put it in a form in the page, you could give your table elements IDs and fetch their contents in the javascript if you really needed to.
Edit: I think maybe it's hard to answer because it's not clear why you want the browser to give you back things that you gave it in the first place. Maybe what you really need is the #SessionAttributes() annotation on your controller so that you can preserve State of the original page shown to the user?
More Edit:
kk, see now. If what you want is Spring web data binding then create a form in parallel as you add more table rows. e.g.,
<form id="myObject" action="whateverYouNeedHere.htm" method="post">
<input type="hidden" id="items[0].name" name="items[0].name" value="foo"/>
<input type="hidden" id="items[0].value" name="items[0].value" value="bar"/>
<input type="hidden" id="items[0].setting" name="items[0].setting" value="buzz"/>
<input type="hidden" id="items[1].name" name="items[1].name" value="foo"/>
<input type="hidden" id="items[1].value" name="items[1].value" value="bar"/>
....
Then just submit that and it will bind right on for you. If you did mean to handle the content yourself, then you probably could use XHR as someone else mentioned.
Use the Spring Data Binding and Validation API to bind it into a Java object of your own design. That documentation is web-agnostic; check out the later chapter to see how the web tier leverages it.
You'll want an abstraction beyond a table, I presume.
in order to stick your table information into a java object, you will first need to send it to the server.. for that you will need to either send it via XHR or in a form.
in order to serialize the object you will need to write some javascript/jquery.
i could write it for you, but your requirements are somewhat vague when it comes to how your table will look, nor do i want to guess about what the java object you want to add your data to looks like.