Showing posts with label Spring MVC. Show all posts
Showing posts with label Spring MVC. Show all posts

Thursday, June 23, 2011

mvc:view-controller

This tag is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked. Use it in static cases when there is no Java Controller logic to execute before the view generates the response.

An example of view-controller that forwards to a home page is shown below:
Source: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html

Tuesday, June 21, 2011

Spring 3.1 M2: Spring MVC Enhancements

Programming Model Improvements

This is the list of programming model improvements introduced in the new @MVC support classes.
  1. Declared @PathVariable arguments are now automatically added to the model. For example this:

  2. is replaced by:


  3. Redirect strings support URI templates expanded with variables from the model (including declared @PathVariables). For example this:

  4. is replaced by:


  5. URI template variables are supported in data binding. For example this:

  6. is replaced by:


  7. Consumable and producible media types can be specified via @RequestMapping. For example this:

  8. is replaced by:

    Besides being shorter the above returns NOT_ACCEPTABLE (406) if the URL matches but the input media type doesn't.

  9. For producible media types this:

  10. is replaced by:

    The above returns a NOT_SUPPORTED_MEDIA_TYPE (415) if the URL matches but the acceptable media type doesn't.

Thursday, June 9, 2011

Using @PathVariable

Let's say that you are creating an user account-based web application in Spring 3.0. You would like to create a controller that would allow users to see each other's profile by using a URL such as
http://myapp/profile/username.

For example:
http://myapp/profile/Juan would show user Juan's profile.
http://myapp/profile/Gaby would show user Gaby's profile.


Spring 3.0's annotated controllers make this kind of mapping easy with the new @PathVariable mapping. As you can see, the RequestMapping for the showProfile method has something a bit unusual: {username}
This is a PathVariable, and it means that this method will serve any request of the format "/profile/someUserName"

We capture the actual username in the next line using the @PathVariable annotation and store it in the variable
final String username
Now we can use it however we want!
Viva Spring framework!!!

Sunday, May 22, 2011

Load Properties in Spring MVC

This is a really trivial case, but I have to cover it, because you never know when you'll need it.

We have our application and we need to load a Properties file and use it, specifically in one of your Controllers, just like this...

I know! When we say spring + properties files, everybody think on this case (don't you?):
But this is not the case I want to cover right now, because the one I want to cover is this one:
String value = (String)properties.get(key);


Ahhhh! That's what I meant :D

How can I do that? Simple, trust in Spring! (may the Spring be with you :P ) By using Util Schema

Piece of cake
Pan comido

Wednesday, May 18, 2011

Log4jConfigListener Deployment Issue on WebLogic

It looks like Spring framework's Log4jConfigListener is having an issue when webapp is deployed as WAR.
Log4jConfigListener is defined in web.xml. I got the below error while deploying the application in weblogic 10.3:

 
weblogic.management.DeploymentException: Cannot set web app root system property when WAR file is not expanded - with nested exception:  [java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded].

The solution is deploy the WAR as exploded or don't use Log4jConfigListener. The spring framework documentation also says the WAR should be exploded.

But... there is a solution available to this without any code change. We just need to set "Archived Real Path Enabled" option checked, just like this:


1. Go to server admin console->Domain-> Web applications. Click the checkbox of Archived Real Path Enabled. This should make an entry into domain config.xml as below. 2. Second option is at webapp level by updating weblogic.xml as below: true The value of set in the web app has precedence over the value set at the domain level. The default value of this property is false.

This is my example:

Wednesday, April 27, 2011

Upload Files with Spring MVC

Have you ever tried to upload a file as part of a form to be submited?
In my case I have a form to add or update products, and each product must have an image (JPG file), besides the regular information related to each product: Name, Description, etc.
Then, we need a form with some inputs and a method on one of my controllers to handle this request and we're set.

This topic is really simple to cover, despite of the fact is poorly covered by the official documentation.
Steps
Add entries on your POM
Add a MultipartResolver in your Web Application Context
On your form don't forget to include enctype attribute and make it POST

Add your input type file as regular HTML


In your controller add a method to handle with all params
I'm using FileUtils to save the uploaded file :D
Look carefully to this parameter @RequestParam("productImage") matches to

And you're all set! Easy, Isn't it?

Wednesday, March 23, 2011

Integration reCaptcha with Spring MVC

When I was explaining about reCaptcha on my previous entry, I made reference to my little-store example app, which basically has a bunch of frameworks (the idea is implement those technologies that I want to learn or just practice).

What I did is really simple, the first step was adding my new dependency to my POM
Then add to my webApplicationContext.xml my new reCaptcha bean
You must get the keys from the official website by adding your site. On my case I put the keys in a properties file, and then by using spring I loaded that file


Next in my Controller I used my ReCaptcha bean, like this
As you could see, this code populates a variable (reCaptcha) which I'm going to display on my JSP using JSTL:
${requestScope.reCaptcha}
Inside of a HTML FORM

Finally, this is how I validated the confirmation text (you must be expecting these 2 params: recaptcha_challenge_field and recaptcha_response_field)

The only problem I faced was related to my flow (which screen should I display), but besides that the implementation is really straight forward, simple!

Sunday, March 20, 2011

reCaptcha - FREE anti-bot service that helps digitize books

Did you remember one of my entries where I implemented jCaptcha???
If you don't know what I'm talking about this is the entry

Now that we understand each other, just for things of the destiny (¬¬ yeah of course!), I found something about "Digitizing Books One Word at a Time" from Google and how many times you've seen this Captcha.


Actually, you can implement it on the same way with jCaptcha, but you need more customization, at the end it has Pros and Cons both solutions, but as an Architect, I take in consideration 2 main factors:
  • Is your App going to be in a closed environment?? Is it going to have access to Internet?? (One thing is that you can access your app through web and something else is that your Network and Server configuration doesn't allow your app to interact with other websites)
  • Do you want to have full control of your App?? Then you don't want to share anything about your app with any external entity, you don't need external Black Boxes (you can re-invent the wheel for you, can't you?)
For this particular situation, I'd prefer to share something with the world, I mean I don't care if Google knows that I'm using its service, My App can share and cooperate with the rest of the world, because I'm not using critical information (for my purposes: Educational)

Then let's begin...
.
What is reCAPTCHA?
reCAPTCHA is a free CAPTCHA service that protects your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human; a CAPTCHA is a Completely Automated Public Turing test to tell Computers and Human Apart. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.


In my next entry I'll be implementing this reCaptcha in my little-store app :)
So I'll see how it works and how hard is to implement it (obviously I'll need to install the library on my local Maven Repo) and use Scriptlets "duh!"
But as people say, if life gives you lemons, make lemonade and that's what I'm going to do

Tuesday, March 15, 2011

Pass parameters from one page to another

This is the issue, I have a JSP which helps me to generate a URL to change the Locale, to switch between Spanish and English, but I have a JSP (maybe more) which is displayed based on a Parameter, because shows the details for an Object based on idObject.
This is my original JSP (So each time I clicked the link, the page was refreshed, but missing the param, obviously the content was never displayed - duh!)

The fix is really simple, just add more params to each URL, by using JSTL :) Like this (creating dynamically my params)

Sunday, March 13, 2011

Spring MVC and Tiles 2

I still remember how cool it was to use Tiles with Struts, back in Mexico and a couple of times here, but since I've migrated my efforts on Spring MVC;
At the very beginning I couldn't implement Tiles successfully (I just tried 2 times :P - 1 really important and another one just for fun)
But when Tiles became an independent project: Apache Tiles 2 things changed a little bit, and now that everything could be delegated to Spring, let's give it a shot!
I didn't have to change too many things, because let's start from an existing App using Spring MVC, Spring Core, Hibernate, Apache CXF, DisplayTag, jCaptcha, etc.

This is my Application layout (yes! I <3 Maven 2!)
 

This is one of my Controllers (something really common)
On the return statement I'm just displaying the file: /jsp/start/landing_page.jsp
This is my previous webApplicationContext.xml (look at the InternalResourceViewResolver - it maps the JSP's to the return statements on my Controllers)

Let's start by integrating Tiles


Add new dependencies in your pom.xml
Update your webApplicationContext.xml (don't forget to take out the existing InternalResourceViewResolver - we're going to replace it with a Tiles View Resolver) by adding these entries
Put more attention to this portion (the rest is a nice to have)
Then according to this tilesConfigurer, I have to add a new file on each JSP folder (views.xml) and my layouts, like this
 

layouts.xml
default.jsp
footer.jsp. Look at the links, because this is the key to make this APP Multilanguage (besides the entries on webApplicationContext.xml and obviously the *.properties files)
 

views.xml on /jsp/start/ folder
This portion makes the magic (
without touching any single line of code!!! )
Where else have you seen "start/landing_page" before? If you don't remember, in my controller (return statement: return "start/landing_page";//show jsp)

And now you're ready to rock!

Wednesday, March 9, 2011

JCaptcha & Spring MVC

Have you ever heard about Captcha.
Is this familiar?

Now that you remember what I'm talking about, let's begin.
I chose JCaptcha, because I used before with Struts back in Mexico for one of my projects when I was working in Government (SICOSIEM) and it was really useful (but I used a servlet)
Now the idea will be implementing the same project on an existing Spring MVC App, which is really simple :)
First things first!. Get JCaptcha and install it in your Local MVN Repo (version 1.0-all), because if you add as dependency version 1.0, it will not work, due to the lack of some jars on Maven Central Repo.
My Controller which will behave like my old servlet (I just have to create an IMG tag with src="/myAppContext/captcha/captcha.htm")
This is how you have to use it (on my previous jsp I have an input text called "captchaText" which holds the value entered by the user)
This is a minimal configuration (I have the bad habit of splitting all my configurations to make my life easier, on this case I'll call this configuration file "jcaptcha.xml"), if you want to dig deeper, you can explore the official web site and play around with other classes (just look into this package: com.octo.captcha.engine.image.gimpy)
FYI: This is the captcha service I'm injecting in my Controllers
Don't forget adding your new configuration file for JCaptcha in your Spring App Context (this is my web.xml)
If you want to see a more complex ("customized") configuration, you can use see this one (It took me a while to create it - but I used as reference what is on JCaptcha WebSite)

Monday, March 7, 2011

Mapping 2 or more URL patterns with same servlet

We have a simple Spring MVC servlet (as usual), nothing out of normal.
With its respective mapping
This is the tricky part, I want to map some weird request mappings like: *.htm or *.jspx (besides *.do)
  • registerCustomer.do
  • registerCustomer.htm
  • registerCustomer.jspx

The solution is simple, just add another entry to your servlet-mapping: The only restriction is to use web-app version=2.4 or 2.5
I always use 2.4 and I didn't have anything else to do. But for educational purposes I updated my web.xml (web app descriptor) for my future developments.

Friday, August 13, 2010

Spring MVC - Binding VO to a Form

Problema:
I have a VO and I wanted to populate it on my JSP and on my controller just process the VO already populated.

Solution:

On my POST method I'll handle my VO already populated.
This entry will do 50% of the job @ModelAttribute(value="LoggerVO") LoggerVO loggerVO
On my JSP I'll map using spring's tag library
By doing this modelAttribute="LoggerVO" commandName="LoggerVO"
I'm matching what I have on my form and what I have on my Controller
I hope this will help you!
Salu2

Monday, August 9, 2010

Adding Spring Web MVC part 2

Now I'll show you a couple of examples how it looks like a Controller & a JSP using Spring MVC.

From my personal perspective Defining a controller gives you a lot of power, because you can define a method to handle RequestMethod.GET, just to show a Form, and another method to handle the RequestMethod.POST to handle the "submit", cool isn't it?

By adding @Controller you already told Spring, "hey this dude is going to be a Controller".

@RequestMapping(value="/configuration/*") means: "If my URL is WebContext/configuration/ this Controller is going to handle the Request"

Then on each method I can define my path below /configuration/ @RequestMapping(value = "showConsumersConfiguration.do"), something like this WebContext/configuration/showConsumersConfiguration.do

I almost forgot @Autowired which is for inject implementation of that Bean


If you want to handle an object like a form (bind an object to a form), check this out

Important, include these tag libraries!

By using this attribute modelAttribute="UserVO" of form:form tag, I'm binding this line of my controller: modelMap.put("UserVO", userVO); with my form

If you see carefully, each attribute of my VO, has a reference on my JSP, at least as hidden field, but all of them are there

Now my form has been binded to my VO @ModelAttribute UserVO paramUserVO

Now you're ready to play around with this thing!!!

Always go to the official documentation to get more details!!!

Adding Spring Web MVC

I'll try to be brief.

Basically, you need to add a new Servlet on you web.xml, a configuration file (let's call it webApplicationContext.xml) and some Annotations.

This is my example:

My web.xml

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml (webApplicationContext-servlet.xml) in WEB-INF by default, but if you provide parameter "contextConfigLocation" you can define a location and name for your configuration file.

My webApplicationContext.xml

Which basically is divided in 3 sections:

  • We're going to use configuration based onn annotations
  • Location of my Controllers
  • And where are located my JSP's

In my next entry I'll cover how it looks like a Controller & JSP.

Sunday, June 27, 2010

WebServices with CXF - Configuration files - web.xml

Sunday, May 23, 2010

WebServices with CXF - My Service interface & Impl

Like with our DTO's, later this code will be having some changes when Apache CXF is called to scene.

Now this is my implementation, as you see I'm becoming fan of the use of annotations. I feel like "NIƑO CHIQUITO" (child) with new toy.

In future entries I'll explain the configuration files involved to attach together Hibernate, Spring and Apache CXF.
But for now, let'f finish with Hibernate+Spring part and then we'll integrate with Apache CXF (then we'll talk about confuration files)

Hasta luego!

WebServices with CXF - My DTO's

For your DTO's youmust apply the same rule like with every Java Bean (getter's & setter's, toString, hashCode, equals & Serialization)

My first step is creating a base DTO with all common fields and methods, then it's just extending from that class. I'll just put 2 examples, Ok?

Later we'll have to retake this objects, because we'll have add some extra lines (anotations) just to make them compatible with our WebServices framework, it will be fun.

Saturday, April 17, 2010

WebServices with CXF - My Pojos & DAOs

First thing, is a good practice declaring methods equals and hashCode
You know what, I'll skip these methods on my code, eclipse can do it for you, don't be lazy!!!
And one more thing, as Architect it's a must declaring toString method, because when you're debugging these method it's going to be really helpful, and you know what... declare toString it's a must too.
The next step is explain what are those annotations, well they're Java 6 annotations, so we can skip some configurations and declare them into our code. I'll try to explain as simple as possible these annotations, let's analyze them:
What I'm doing here is just declaring that this POJO will be an Entity which maps to a table called EDITOR

Using Annotations, I declared that editorId is my PK which basically is AutoIncremental and to which column will be mapped. With columns is really easy.
But what about relations??? Like
BOOK >-- EDITOR
In this case I just declared what I needed to declare: One Editor has Many books using a List of Book, like in every mapping of Hibernate: the most common fetching strategy to be used will be LAZY; basically what I did was linking the current ENTITY by it's PK (mappedBy="editor") to Book
So in Book this is what we have to do (the inverse to OneToMany and define an Editor for each Book, so each child will have a reference to it's Dad):

The last thing is just declare which column & attribute will be used to do the JOIN between child and father


You can get more details if you look for that topic in Hibernate official documentation.
And these are my DAO's (I just included 1 as example), others should be similar. Always code oriented to interfaces! Later you'll thank me. In my next entry I will explain my Services and we'll be ready for using CXF.