spring and hibernate - spring-mvc

I am beginner with spring, I have a search form and I want to error or the form is blank it sends me to the error page otherwise it sends me to the page result.
if anyone can help me
thank you
here is my code.
#SuppressWarnings( { "unchecked" })
#RequestMapping("/search.html")
public String findAllData(Map model, SearchForm seachForm) {
model.put("allData", searchService.searchData(seachForm));
if("seachForm"!=null)
{
return "displayForm";
}
else
{
return "redirect:/searchForm.htm";
}

if("seachForm"!=null){
return "displayForm";
}else{
return "redirect:/searchForm.htm";
}
seachForm is not a String, try with
if(seachForm != null){
return "displayForm";
}else{
return "redirect:/searchForm.htm";
}
Greetings.

As MG_Bautista showed searchForm is definitely not a String (you should have gotten a compile error), but searchForm would also never be null. It'll just be a bunch of zero-length Strings. You have to do iterate over all fields of searchForm like
if ("".equals(searchForm.getUserName()) &&
"".equals(searchForm.getAddress())) {
return "displayForm";
} else {
return "redirect:/searchForm.htm";
}

Related

what is the best practice of Vert.x handler for checking check existence?

I am implementing a method using Vertx to check the existence of certain value in the database and use Handler with AsyncResult.
I would like to know which one is the best practice:
Option 1: When nothing found, Handler is with succeededFuture but with result as FALSE:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Boolean>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
resultHandler.handle(Future.succeededFuture(foundIt));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: When nothing found, Handler is with failedFuture:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Void>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
// HERE IS THE DIFFERENCE!!!
if (foundIt) {
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture("Item " + itemToFind + " not found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
UPDATE:
Let's say I have another example, instead of checking the existence, I would like to get all the results. Do I check the Empty results? Do I treat Empty as failure or success?
Option 1: only output them when it's not null or empty, otherwise, fail it
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
if (items != null && !items.empty()) {
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture("No items found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: output results I got, even though it could be empty or null
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
The 1st one option is better, because you can clearly say, that checkExistence returned True or False and completed successfully or it failed with some exception (database issue, etc.).
But lets say, you've decided to stick with 2nd option. Then, imagine you have another method:
void getEntity(int id, Handler<AsyncResult<Entity>> resultHandler);
If entity with provided id doesn't exists, will you throw exception (using Future.failedFuture) or return null (using Future.succeededFuture)? I think, you should throw exception to make your methods logic similar to each other. But again, is that exceptional situation?
For case with returning list of entities you can just return empty list, if there are no entities. Same goes to single entity: it's better to return Optional<Entity> instead of Entity, because in this way you avoid NullPointerException and don't have nullable variables in the code. What's better: Optional<List<Entity>> or empty List<Entity>, it's open question.
Particularly if you're writing this as reusable code, then definitely go with your first option. This method is simply determining whether an item exists, and so should simply return whether it does or not. How is this particular method to know whether it's an error condition that the item doesn't exist?
Some caller might determine that it is indeed an error; it that's the case, then it will throw an appropriate exception if the Future returns with false. But another caller might simply need to know whether the item exists before proceeding; in that case, you'll find yourself using exception handling to compose your business logic.

How to show intro text only in news website (asp.net mvc)

I have a function in my view:
#helper truncate(string input, int length)
{
if (input.Length<=length)
{
#input;
}
else
{
#input.Substring(0,length)#:...
}
}
If i write #truncate("some word",50) => it worked
But i write #truncate(item.Description, 50) => it error: Object reference not set to an instance of an object.
Please help me to fix my problem or show me another way to show intro text only in my site
Thanks!
if input is null, then you get error input.Length and input.Substring lines. You should check, if it is not null.
#helper truncate(string input, int length)
{
if(input == null)
{
//
}
else
{
if (input.Length <= length)
{
#input;
}
else
{
#input.Substring(0,length)#:...
}
}
}
EDIT (after comment)
you can use:
input = Regex.Replace(input , "<.*?>", string.Empty);
NOTE: Html.Raw returns markup that is not HTML encoded.

Asp.Net validation check at client side

I am validating data at client side in asp.net validator by using following code snipet.
function ValidateData(){
if (!Page_ClientValidate("Validator1") || !Page_ClientValidate("Validator2")) {
return false;
}
else{
return true;
}
I called it on submit of button. But it showing validation messages of Validator1 group. Its not showing me validation messages of Validator2 group.
Just gone through :
see this link question , here its told - || operator short-circuits if the left condition is true.
Does a javascript if statement with multiple conditions test all of them?
If you want both , then cant you try like this :
function ValidateData(){
if (!Page_ClientValidate("Validator1"))
{
if (!Page_ClientValidate("Validator2"))
{
return false;
}
else
{
return false;
}
return false;
}
else
{
return true;
}
}
Just a random try , this code :)
Rigin

ASP.NET Entity Framework DataContext use issue

I 've built an ASP.NET website using EF. I created a DataContext class which implements the singleton pattern. My DAO classes (singletons too) instanciate this datacontext and store it in a property. They use it in order to query the SQLServer DataBase. This worked ok for 3 months but I suddenly got exception messages like :"Connection must be valid and open / connection already open". It seemed that datacontext was not disposed. The only change, according to me, was the data size and number of users increasing.
I then found multiple posts saying that singleton was a bad idea foe datacontext, so I tried to instanciate datacontext in a using statement in every request and that resolved the problem, except for update queries which had no effects in database. I had to attach the db object to the context and then set its EntityState to "modified" to have my SaveChanges work.
Like this :
public bool DoucheXpsu(as_headers session) {
using (MyDBEntities MyContext = new MyDBEntities()) {
try {
as_status status = GetStatus(session);
if (status != null) {
if (status.mainstatusvalue == 300) {
status.DateDoucheXpsu = DateTime.Now;
status.DoucheXpsu = 1;
MyContext.as_status.Attach(status);
MyContext.ObjectStateManager.ChangeObjectState(status, EntityState.Modified);
MyContext.SaveChanges();
return true;
} else {
return false;
}
} else {
return false;
}
} catch (OptimisticConcurrencyException) {
return false;
} catch (Exception) {
return false;
}
}
}
The problem is that it actually didn't work for ONE method (which has nothing different from the other update method) !
The exception occured as I tried to attach the object : "The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state. " So I had to comment the attach and ChangeObjectState methods to have it work as expected :
public bool SetSessionToDelete(string numSession) {
using (MyDBEntities MyContext = new MyDBEntities()) {
try {
view_headerStatus view = (from v in MyContext.view_headerStatus
where v.CodeSession == numSession
where v.lastinserted == 1
select v).First();
if (view != null) {
as_status status = (from s in MyContext.as_status
where s.jobclsid == view.jobclsid
where s.lastinserted == 1
select s).First();
if (status != null) {
status.DeleteSession = 1;
//MyContext.as_status.Attach(status);
//MyContext.ObjectStateManager.ChangeObjectState(status, EntityState.Modified);
MyContext.SaveChanges();
return true;
} else {
return false;
}
} else {
return false;
}
} catch (OptimisticConcurrencyException) {
return false;
} catch (Exception) {
return false;
}
}
}
The question is WHY should this one behave differently ???
I've read many posts about EF and dataContext but I feel I'm missing something. I would be glad if anyone can help.
Thanks.
In your first example, this line here:
as_status status = GetStatus(session);
I would assume this populates using a DIFFERENT context, and when it leaves the GetStatus() method the context it used to load is disposed. That is why your subsequent Attach() works. However in your second example you do not need to attach because it was loaded using the current (connected) context.
To solve you may want to either pass the context to your methods like GetStatus() resulting in no need to reattach. I don't typically reattach unless I am resurrecting an object over the wire or from a file.

"not all code paths return a value"

namespace Electronic_Filing_of_Appeals
{
public class GenerateXML
{
public ElectronicRecordAppellateCase CreateXml()
{
My lies on the CreateXML() portion of this code. The error being kicked back is
Electronic_Filing_of_Appeals.GenerateXML.CreateXml(): not all code paths return a value
I've tried different approached but the same result.
Any clue from the professionals?
Your method is suppoed to return an instance of ElectronicRecordAppellateCase class. I guess you are returning the result in some If condition in your method or so like this.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
//do something useful
return output;
}
// Not returning anything if the if condition is not true!!!!
}
Solution : Make sure you are returning a valid return value from the method.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
return output;
}
return null; //you can return the object here as needed
}
If you specify output type, your method HAS to provide a value following every path of the code. When you see this error, it means one or more scenarios in your method don't return a value of a specified type, but result in a termination of the method instead.
This is an example of such problematic method:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
// if the something is false, the method doesn't provide any output value!!!
}
This could be solved like this for instance:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
else return null; // "else" isn't really needed here
}
See the pattern?
not all code paths return value means, you function may not return a expected value
you don't show your code so I made a example
for example, the follow function has 3 paths, if parm equal 1, if parm equal 2 but if parm is not equal 1 or 2 don't return a value
function SomeObject foo(integer parm){
if (parm == 1) {
return new SomeObject();
}
if (parm == 2) {
return new SomeObject();
}
//What if parm equal something else???
}

Resources