Posts Tagged ‘Web application’

DebuggingPHP a well-known scripting language used for web development or we can say PHP is the most used scripting language in today’s web industry. Even most of popular CMSs are also developed and support PHP which makes PHP more popular as well. As the users increases respectively (to use PHP language for web development) there is need of PHP debuggers also increase. Because everyone wants that their code should be fine and error free. Debugger tool helps you in debugging errors in web applications and scripts by which makes innovative web development easy. In This post I have mentioned top 10 widely used PHP debuggers by developer, have a look.

Read More »

In this post of Upload Multiple Images with Jquery code allows to user can select and upload multiple images in single shot, Quick look this live demo. Download Script     Live Demo Sample database design for Users. Users Contains user details username, password, email, profile_image and profile_image_small etc. CREATE TABLE `users` ( `user_id` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email`…

Read More »

 

JavaServer Faces(JSF) 2. 0, is usually an MVC web framework which usually concentrate on simplifies constructing User interfaces (comes with 100+ ready USER INTERFACE tags) for Java web app as well as create reusable USER INTERFACE component simple to put into practice. Not like JSF 1.x back button, every little thing is expressed inside faces-config. xml, together with JSF 2. 0, you might be allowed to make use of annotation to be able to state navigating, manage bean or maybe CDI bean, which can make ones development much easier as well as faster.

In this particular short tutorial, it offers a superior quite a few comprehensive good examples as well as explanations in applying JavaServer Faces(JSF) 2. 0 framework.

Some quick start examples for JSF 2.0

Quick Start JSF 2.0

Managed Bean

 

 

English: Logo of Apache Struts

Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

package net.viralpatel.struts.validation.form;
import org.apache.struts.validator.ValidatorForm;
public class CustomerForm extends ValidatorForm {
    
    private String name;
    private String telephone;
    private String email;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

<!-- Validator Configuration -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
        value="/WEB-INF/validator-rules.xml,
                /WEB-INF/validation.xml" />
</plug-in>

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

<?xml version="1.0" encoding="UTF-8" ?>
<!--DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
    <constant>
    <constant-name>telephoneFormat</constant-name>
    <constant-value>^\d{5,10}$</constant-value>
    </constant>
</global>
<formset>
    <form name="CustomerForm">
        <field property="name" depends="required">
            <arg key="label.name" />
        </field>
        <field property="age" depends="required, integer, intRange">
            <arg0 key="label.age" />
            <arg1 key="${var:min}" resource="false"/>
            <arg2 key="${var:max}" resource="false"/>
            <var>
                <var-name>min</var-name>
                <var-value>1</var-value>
            </var>
            <var>
                <var-name>max</var-name>
                <var-value>125</var-value>
            </var>
        </field>
        <field property="telephone" depends="required, mask">
            <arg key="label.telephone" />
            <arg1 key="label.telephone" />
            <var>
                <var-name>mask</var-name>
                <var-value>${telephoneFormat}</var-value>
            </var>
        </field>
        <field property="email" depends="email">
            <arg0 key="label.email" />
            <arg1 key="label.email" />
        </field>
    </form>
</formset>
</form-validation>

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

<form-beans>
    <form-bean name="CustomerForm"
        type="net.viralpatel.struts.validation.form.CustomerForm" />
</form-beans>
...
...
...
<action-mappings>
...
    <action path="/customer" name="CustomerForm" validate="true"
        input="/index.jsp"
        type="net.viralpatel.struts.validation.action.CustomerAction">
        <forward name="success" path="/Customer.jsp" />
        <forward name="failure" path="/index.jsp" />
    </action>
...
</action-mappings>

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).

label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age
# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL></font>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>Struts Validation Framework example.</title>
</head>
<body>
<html:errors />
<html:javascript formName="CustomerForm" />
<html:form action="/customer">
    <bean:message key="label.name" />
    <html:text property="name"></html:text>
    <br />
    <bean:message key="label.age" />
    <html:text property="age"></html:text>
    <br />
    <bean:message key="label.email" />
    <html:text property="email"></html:text>
    <br />
    <bean:message key="label.telephone" />
    <html:text property="telephone"></html:text>
    <br />
    <html:submit value="Submit"></html:submit>
</html:form>
</body>
</html>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.

struts-validator-form-screen2

Reference :http://viralpatel.net

English: Logo of Русский: Логотип Apache Tomcat

Setting the JAVA_HOME , CATALINA_HOME Environment Variable on Windows

One can do using command prompt
1. set JAVA_HOME=C:\”top level directory of your java install”
2. set CATALINA_HOME=C:\”top level directory of your Tomcat install”
3. set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Or you can do the same

  1. Go to system properties.
  2. Go to environment variables and add a new variable with the name  JAVA_HOME and provide variable value as C:\”top level directory of your java install”.
  3. Go to environment variables and add a new variable with the name  CATALINA_HOME and provide variable value as C:\”top level directory of your Tomcat install”.
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

and write startup.bat on command Prompt and press enter tomcat will start up and for shutdown u just write shutdown.bat        once you start the tomcat you can access it like that http://localhost:8080     and access Application Manager using login and password …. if you dont know username and password you can  follow below instructions ….

User and password for Tomcat

By default, Tomcat does not enable admin or manager access. To enable it, you have to edit the “%TOMCAT_FOLDER%/conf/tomcat-users.xml” manually.

File : tomcat-users.xml (before update) , initially, Tomcat comments all users and roles like above.



<!--
  
  <role rolename="role1"/>
  
  
  
-->

File : tomcat-users.xml (after updated)

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>
</tomcat-users>

To enable admin access, just update the content like above. Saved it and restart Tomcat, now you can access Tomcat admin or manger pages with user = “admin” and password = “admin“.

Introduction
This document is one of a series of tutorials to demonstrate the use of the Web Services tools in the Web Tools Platform Project using the WTP 1.5 drivers.
This tutorial shows how to create a simple Web service and Web service client from a Java class. The Java class in this scenario converts between the Celsius and Farenheit temperature scales.
Set Up
Before creating the Web service, there are two prerequisites:
  1. Install Apache Tomcat
  2. Create a dynamic Web project called ConverterProj .
Creating a bottom up Java bean Web service and Web service client
  1. Import the wtp/Converter.java class into ConverterProj/src (be sure to preserve the package).
  2. Select the Converter.java file.
  3. Open File -> New -> Other… -> Web Services -> Web Service.
  4. Click Next.
  5. Move the Service slider to the Start Service position .
  6. Move the Client slider to the Test Client position .
  7. Select Monitor the Web service .
  8. If you want to choose a server different from the one defaulted by the wizard, click the Server project link to select a server .
  9. Result:

  1. Click Finish .
  2. It will take about one minute for the wizard to assemble the Web service and Web service client Web projects,
  3. start Apache Tomcat, and deploy the projects to Tomcat. Once finished, the generated Sample JSP Web
  4. application will appear in the browser view, maximized here for clarity:

  1. Under Methods , click on celsiusToFarenheit(float) .
  2. Under Inputs , enter 37 into the celsius entry field.
  3. Click on Invoke. In the Result view, you should get a response of 98.6.

  1. Since you selected the “Monitor Web service” checkbox, a TCP/IP port is automatically created on the
  2. Tomcat server. When you invoke the Web service, the TCP/IP Monitor view comes up automatically
  3. showing the SOAP message request and response. Double-click on the TCP/IP Monitor view and
  4. select XML view in the drop-down combo for both request and response. Result:

Explanation
The Web Service wizard is orchestrating the end-to-end generation, assembly, deployment, installation and execution of the Web service, Web service client, and sample JSPs. In this scenario, we clicked Finish on page one. In effect, this is allowing the wizard to pick reasonable defaults according to the basic high-level choices made on the first page. If you repeat this scenario, but use the Next button to work through the wizard, you will learn more about the kinds of choices that are available and the kinds of defaults being assumed.
After completing this scenario, the WSDL for the Converter Web service can be found in ConverterProj/WebContent/wsdl/Converter.wsdl.
Now that your Web service is running, there are a few interesting things you can do with this WSDL file. Examples:
  1. You can double-click on the WSDL to open the WSDL graphical editor.
  2. You can right-click on the WSDL and choose Web Services -> Test with Web Services Explorer to test the service.
  3. You can right-click on the WSDL and choose Web Services -> Publish WSDL file to publish the service to a public UDDI registry.
  4. You can click on the WSDL and choose New -> Other… -> Web Services -> Web Service Client to generate a Web service client. Note, however, that we have already witnessed the internal and visual features of the Web Service Client wizard since, in addition to being its own wizard, it is quite literally embedded within the larger Web Service wizard.

 

Recently I had a requirement where using Spring MVC we had to take inputs multiple rows of data from user. The form had many rows which user can edit and submit. Spring MVC provides very simple yet elegant way of collecting data from multiple rows from HTML form and store them in List of Beans in Java.

18% Price Drop: Samsung 51" Black Plasma 720P HDTV – PN51E450

Lets look at the requirement first. We have a screen where data for multiple Contacts is displayed. The Contact data is displayed in an HTML table. Each row in the table represents a single contact. Contact details consist of attributes such as Firstname, Lastname, Email and Phone number.

Related: Spring 3 MVC Tutorial Series (Must Read)

The Add Contact form would look like following:
spring-mvc-multi-row-form

Lets see the code behind this example.

Tools and Technologies used:

  1. Java 5 or above
  2. Eclipse 3.3 or above
  3. Spring MVC 3.0

Step 1: Create Project Structure

Open Eclipse and create a Dynamic Web Project.
eclipse-dynamic-web-project

Enter project name as SpringMVC_Multi_Row and press Finish.

Step 2: Copy Required JAR files

Once the Dynamic Web Project is created in Eclipse, copy the required JAR files under WEB-INF/lib folder. Following are the list of JAR files:
spring-mvc-multi-row-jar-files

 

Step 3: Adding Spring MVC support

Once the basic project setup is done, we will add Spring 3 MVC support. For that first modify default web.xml and add springs DispatcherServlet.

File: /WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3MVC-Multi-Row</display-name>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

Related: Tutorial: Learn Spring MVC Lifecycle

Now add spring-servlet.xml file under WEB-INF folder.

File: /WebContent/WEB-INF/spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        
    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.spring3.controller" />  
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Note that in above spring-servlet file, line 10, 11 defines context:annotation-config and component-scan tags. These tags let Spring MVC knows that the spring mvc annotations are used to map controllers and also the path from where the controller files needs to be loaded. All the files below package net.viralpatel.spring3.controller will be picked up and loaded by spring mvc.

Step 4: Add Spring Controller and Form classes

File: /src/net/viralpatel/spring3/form/Contact.java

package net.viralpatel.spring3.form;
public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String phone;
    public Contact() {
    }
    public Contact(String firstname, String lastname, String email, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.phone = phone;
    }
    
    // Getter and Setter methods
}

File: /src/net/viralpatel/spring3/form/ContactForm.java

package net.viralpatel.spring3.form;
import java.util.List;
public class ContactForm {
    private List<Contact> contacts;
    public List<Contact> getContacts() {
        return contacts;
    }
    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }
}

Note line 7 in above code how we have defined a List of bean Contact which will hold the multi-row data for each Contact.

File: /src/net/viralpatel/spring3/controller/ContactController.java

package net.viralpatel.spring3.controller;
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ContactController {
    
    private static List<Contact> contacts = new ArrayList<Contact>();
    static {
        contacts.add(new Contact("Barack", "Obama", "barack.o@whitehouse.com", "147-852-965"));
        contacts.add(new Contact("George", "Bush", "george.b@whitehouse.com", "785-985-652"));
        contacts.add(new Contact("Bill", "Clinton", "bill.c@whitehouse.com", "236-587-412"));
        contacts.add(new Contact("Ronald", "Reagan", "ronald.r@whitehouse.com", "369-852-452"));
    }
    
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ModelAndView get() {
        
        ContactForm contactForm = new ContactForm();
        contactForm.setContacts(contacts);
        
        return new ModelAndView("add_contact" , "contactForm", contactForm);
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) {
        System.out.println(contactForm);
        System.out.println(contactForm.getContacts());
        List<Contact> contacts = contactForm.getContacts();
        
        if(null != contacts && contacts.size() > 0) {
            ContactController.contacts = contacts;
            for (Contact contact : contacts) {
                System.out.printf("%s t %s n", contact.getFirstname(), contact.getLastname());
            }
        }
        
        return new ModelAndView("show_contact", "contactForm", contactForm);
    }
}

In above ContactController class, we have defile two methods: get() and save().

get() method: This method is used to display Contact form with pre-populated values. Note we added a list of contacts (Contacts are initialize in static block) in ContactForm bean object and set this inside a ModelAndView object. The add_contact.jsp is displayed which in turns display all contacts in tabular form to edit.

save() method: This method is used to fetch contact data from the form submitted and save it in the static array. Also it renders show_contact.jsp file to display contacts in tabular form.

Step 5: Add JSP View files

Add following files under WebContent/WEB-INF/jsp/ directory.

File: /WebContent/WEB-INF/jsp/add_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
<h2>Spring MVC Multiple Row Form Submit example</h2>
<form:form method="post" action="save.html" modelAttribute="contactForm">
    <table>
    <tr>
        <th>No.</th>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
        <tr>
            <td align="center">${status.count}</td>
            <td><input name="contacts[${status.index}].firstname" value="${contact.firstname}"/></td>
            <td><input name="contacts[${status.index}].lastname" value="${contact.lastname}"/></td>
            <td><input name="contacts[${status.index}].email" value="${contact.email}"/></td>
            <td><input name="contacts[${status.index}].phone" value="${contact.phone}"/></td>
        </tr>
    </c:forEach>
</table
<br/>
<input type="submit" value="Save" />
    
</form:form>
</body>
</html>

In above JSP file, we display contact details in a table. Also each attribute is displayed in a textbox. Note that modelAttribute=”contactForm” is defined in <form:form /> tag. This tag defines the modelAttribute name for Spring mapping. On form submission, Spring will parse the values from request and fill the ContactForm bean and pass it to the controller.

Also note how we defined textboxes name. It is in form contacts[i].a. Thus Spring knows that we want to display the List item with index i and its attribute a.

contacts[${status.index}].firstname will generate each rows as follows:

contacts[0].firstname // mapped to first item in contacts list
contacts[1].firstname // mapped to second item in contacts list
contacts[2].firstname // mapped to third item in contacts list

Spring 3 MVC and path attribute and square bracket

One thing here is worth noting that we haven’t used Spring’s
tag to render textboxes. This is because Spring MVC 3 has a unique way of handling path attribute for
tag. If we define the textbox as follows:

<form:input path="contacts[${status.index}].firstname" />

Then instead of converting it to following HTML code:

<input name="contacts[0].firstname" />
<input name="contacts[1].firstname" />
<input name="contacts[2].firstname" />

It converts it into following:

<input name="contacts0.firstname" />
<input name="contacts1.firstname" />
<input name="contacts2.firstname" />

Note how it removed square brackets [ ] from name attribute. In previous versions of Spring (before 2.5) the square bracket were allowed in name attribute.

It seems w3c has later changed the HTML specification and removed [ ] from html input name.
Read the specification http://www.w3.org/TR/html4/types.html#type-name. It clearly says that:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

Thus, square brackets aren’t allowed in name attribute! And thus Spring 3 onwards this was implemented.

So far I haven’t got any workaround to use springs <form:input /> tag instead of plain html <input /> to render and fetch data from multiple rows.

File: /WebContent/WEB-INF/jsp/show_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
<h2>Show Contacts</h2>
<table width="50%">
    <tr>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
        <tr>
            <td>${contact.firstname}</td>
            <td>${contact.lastname}</td>
            <td>${contact.email}</td>
            <td>${contact.phone}</td>
        </tr>
    </c:forEach>
</table
<br/>
<input type="button" value="Back" onclick="javascript:history.back()"/>
</body>
</html>

File: /WebContent/index.jsp

<jsp:forward page="get.html"></jsp:forward>

 

Final Project Structure

Once we have added all relevant source files and jar files, the project structure should look like following:
spring-multi-row-project-structure

 

Step 6: Execute it

Execute the web application Right click on project > Run As > Run on Server.

Add Contact page

Show Contact page
spring-multiple-row-list-show-page

Download Source Code

Spring-MVC-Multiple-Row-List-example.zip (2.9 MB)

Enhanced by Zemanta

IIS

Java platform is extremely successful in building robust and high performance web applications. Platform independence is one of the strength of Java engine and Helicon Zoo now provides a convenient way to deploy and run Java web applications on Windows platform with Microsoft IIS. To deploy Java Servlet application on IIS 7 you will only need to follow this simple instruction:

Platfrom installation

  1. Download and install Web Platform Installer.
  2. Run Web Platform Installer and click “Options”.
  3. Add Helicon Zoo feed into Display additional scenarios box:  http://www.helicontech.com/zoo/feed. New “Zoo” tab will appear.
  4. Go to the Zoo, Packages and install Java Hosting Package.
  5. Accept licenses to start installation process.

Alternatively, instead of installing Java Hosting Package you can install Modules –> Helicon Zoo Module and Engines –> Jetty separately. This is minimal requirement to run Java Servlet applications under Microsoft IIS web server. If you want to run Java Servlets under IIS Express and WebMatrix in your development environment, then you will also need to install Helicon Zoo Module for IIS Express form Engines section.

This is enough configuration to run most of Java Servlet applications directly form IIS.

Installing application

Launch IIS Manager and create new web-site or an application within a web-site. Copy your Java application into the root folder of this IIS application. Java application could be either a single .war file or set of unpacked files with directory structure, including web-inf folder. Then just create the following web.config:

 <?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <heliconZoo>
      <application name="jetty.project" >
        <environmentVariables>
          <!-- Uncomment line below if you want to set contexts directory -->
          <!--  <add name="CONTEXTS_DIR" value="%APPL_VIRTUAL_PATH%" /> -->

          <!-- Optional variables: -->
          <!-- <add name="CONTEXT_PATH" value="%APPL_VIRTUAL_PATH%" /> -->
          <!-- <add name="WAR_EXTRACT_PATH" value="%APPL_PHYSICAL_PATH%" /> -->

          <!-- A WAR file or start directory to run -->
          <add name="WAR_FILE" value="my_application.war" />
        </environmentVariables>
        </application>
    </heliconZoo>

        <handlers>
          <add name="jetty.project#x86" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x86"
            preCondition="bitness32" resourceType="Unspecified"
            requireAccess="Script" />
          <add name="jetty.project#x64" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x64"
            preCondition="bitness64" resourceType="Unspecified"
            requireAccess="Script" />
        </handlers>
  </system.webServer>
</configuration>

Please take a look at <environmentVariables> section.

  • CONTEXTS_DIR — optional path to directory with .xml files which describe Jetty contexts. If this variable isn’t set, Zoo looks for “contexts” folder in the root of application. If no such folder found, Zoo presumes the application has single context and uses variables described below.
  • CONTEXT_PATH — optional virtual path of the application. Default value is taken from APPL_VIRTUAL_PATH variable.
  • WAR_FILE — optional path to a .war file or directory with extracted application.
  • WAR_EXTRACT_PATH — optional .war file extraction path. Is set to application’s root folder by default.

Here is an example of context.xml file that you may use instead of setting WAR file name explicitly. This allows to run multiple applications and contexts in a single IIS web site.

contexts/context.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">

   <Set name="contextPath">/application</Set>
   <Set name="war">my_application.war</Set>
   <Set name="tempDirectory">application_dir</Set>

</Configure>

WARNING: Since WAR files need to be extracted before execution you will need to have a folder with write permissions.  In default IIS installation all application pools are executed with permissions of IIS_IUSRS group which does not have write permissions to the web application folders. You will need to provide write permissions to the user running Application Pool or IIS_IUSRS group to the folder containing Java application or specify other folder using WAR_EXTRACT_PATH variable with write permissions provided.Now you can open IIS web site in the browser and see your Java web application running.

That’s it! Installation process is clear and automatic and will only take several minutes.

5 Responses to Deploying Java Servlet applications on Windows with IIS

  1. Peter says:

    Downloaded and installed as described in the article (http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/).

    However for some weird reason I can successfully view the Java app via IIS when using http://localhost/appname but if I do the same thing http:///appname on another machine I get a a 404 from IIS and if I do it on the server itself I get a 404 from Jetty instead.

    This is running on a 64bit Win2008R2 Std server VM with an IIS app set up to use a ASP.NET 4.0 integrated app pool.
    The folder the IIS app points to contains the contents of the WAR file, i.e. \web-inf and \xforms-jsp and the web.config with the described contents from the article.

    Any ideas on what could be wrong would be much appreciated.

    • Slavik says:

      Hello.
      Please try and use CONTEXT_PATH variable as follows:
      <add name=”CONTEXTS_PATH” value=”/appname” />

      Make sure “appname” is an application. If it’s not, open IIS manager, navigate to that folder and in the context menu click “Convert to Application”.

  2. jules says:

    I installed on a Windows 7 64 bit machine and then downloaded the jenkins.war file and tried to deploy it:
    But I get:
    HTTP ERROR: 503
    Problem accessing /test. Reason:
    Service Unavailable
    Powered by Jetty://

    ??

    • Slov says:

      I think installing Jenkins on IIS may deserve a separate article.
      First you will need to upgrade your Jetty installation as we have fixed some functions. Just delete C:\jetty folder and install again using Helicon Zoo feed.
      Then you will need to use contexts folder, instead of setting WAR file explicitly as Jenkins require additional configurations.
      Please remove all “environmentVariables” from web.config, create contexts folder, and create context.xml file in this folder with the following content:

      < ?xml version=”1.0″?>
      < !DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”&gt;

      Test Realm
      /jenkins
      jenkins.war

      After that navigate to http://localhost/jenkins (not to the root folder). It should work now.

      • Slov says:

        A bug with tags. Try again:

        <?xml version=”1.0″?>
        <!–DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”>–>

        <Configure class=”org.eclipse.jetty.webapp.WebAppContext”>
        <Get name=”securityHandler”>
        <Set name=”loginService”>
        <New class=”org.eclipse.jetty.security.HashLoginService”>
        <Set name=”name”>Test Realm</Set>
        </New>
        </Set>
        </Get>

        <Set name=”contextPath”>/jenkins</Set>
        <Set name=”war”>jenkins.war</Set>
        <Set name=”tempDirectory”>jenkins</Set>
        </Configure>

Reference :http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/

Exquisite-print printer

Below the UN-commented  code is the in which you just give the path of the directory which contains files …. now the code see the files and send all files to the printer.

“I make that code for bulk of files send to printing in one time”

 

 

 
package javaapplication1;/*

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;

/**
*
* @author zeeshan
*/
public class JavaApplication1 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, PrintException {
// TODO code application logic here which show u GUI of printer

//        FileInputStream textStream;
//        textStream = new FileInputStream(“C:\\\Users\\Zeeshan\\Desktop\\interestrates.xlsx”);
//        PrintRequestAttributeSet attributes =
//                new HashPrintRequestAttributeSet();
//        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
//        Doc mydoc = new SimpleDoc(textStream, flavor, null);
//        PrintService[] services = PrintServiceLookup.lookupPrintServices(
//                flavor, attributes);
//        PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//
//        if (services.length == 0) {
//            if (defaultService == null) {
//                //no printer found
//            } else {
//                //print using default
//                DocPrintJob job = defaultService.createPrintJob();
//                job.print(mydoc, attributes);
//
//            }
//
//        } else {
//
//            //built in UI for printing you may not use this
//            PrintService service = ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, attributes);
//
//
//            if (service != null) {
//                DocPrintJob job = service.createPrintJob();
//                job.print(mydoc, attributes);
//            }
//
//        }

try {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));

/*  Online Printer Lists and select which you like
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0) {
throw new RuntimeException(“No printer services available.”);
}
PrintService ps = pss[3];
*/
/* Default Printer */
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService ps = defaultService;
System.out.println(“Printing to ” + ps);
DocPrintJob job = ps.createPrintJob();
String files;
File folder = new File(“C:\\Users\\Zeeshan\\Desktop\\pics\\”);
File[] listOfFiles = folder.listFiles();

for (int i = 2; i < listOfFiles.length; i++) {

if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
FileInputStream fin = new FileInputStream(folder.getPath()+”\\” + files);
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);

job.print(doc, pras);
fin.close();
System.out.println(files);
}
}

} catch (Exception e) {
e.printStackTrace();
}

}
}

hi dear’s

I am caught in the problem that when i use “Form ENCTYPE=”multipart/form-data” and Method=”Post” and ACTION=”FileProcess.jsp” then i am get the file on FileProcess.jsp but i can’t get the other data

like example Problem Post by that Some Person

______________________________________________________________________________________________

http://www.velocityreviews.com/forums/t137597-html-file-upload-using-enctype-multipart-form-data-in-form.html

Should we use enctype=multipart/form-data in the form, I know it is recommended
if the form has <input type=”file”>. My form has and other
html controls.

I tried the following,

form.html
=========

POST” enctype=multipart/form-data>”

 

<input type=text name=”name” size=80>”

filename” size=80>”

<input type=”submit” value=”Upload File Test”>’
“</FORM>”

test.jsp
=========
<p><%= “filename = ” + request.getParameter(“filename”) %>
<p><%= “name = ” + request.getParameter(“name”) %>

It will output
filename = null
name = null

I don’t understand why, but if i remove enctype=multipart/form-data in the form,
then I am able to get the data.
Please advise. Thanks!!

_______________________________________________________________________________________________

Now i think you Have Clear Picture in Your Mind …….

Now i am going to tell you solution which i get From My RND and Try………..

1)Test.jsp

"!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
html
 "   head
script
             var e="";
function selValue(){
                //  alert('me there');
                e = document.getElementById("name");
                //   alert('me there ='+e);
                if(e=="")
                {
                    alert('Please Select');

                }else{

                    window.location.replace("Accountdetials.jsp?value="+e);
                }//  window.location="<%= request.getContextPath() + "/Test.jsp"%>"+"?value="+e;

            }
/script
<scriplet 
String selectedindex = "";

            String AccountStatus = request.getParameter("value");
            if (AccountStatus != null) {

                System.out.println("value=" + AccountStatus);
                session.setAttribute("AccountStatus", AccountStatus);

            } else {
                session.setAttribute("AccountStatus", null);
            }
/secriplet

body
FORM ENCTYPE="multipart/form-data" ACTION="FileProcess.jsp" METHOD=POST>

center>
table border="0" bgcolor=#ccFDDEE>
tr>UPLOAD THE FILE
tr> 
INPUT NAME="name" TYPE="text"
Choose the file To Upload:
INPUT NAME="file" TYPE="file"

input type="submit" value="Send File" 
table>
center> 
FORM>
BODY>
HTML>

 In above page you see one is <input and="" other="" input="" now="" when="" we="" use ="" "form="" enctype="multipart/form-data" then="" can't="" get="" data="" on="" page="" like="" that 
 boz now you data is send in multiparts for that reason we get file data like that which i tell in the below  FileProcess.jsp  now get the file data in the below page but not get the intput Type="text" data ..... now for that i use JAVASCRIPT like that now you can see the above Javascript function selValue(); then scriptlet of jsp how i put it in the session now when 
you press the Submit button the value of input text is all ready in the session .... now on next action jsp page just 
get that value from session 
I can do this on the Select Option tag ...... 

2)FileProcess.jsp

<scriplet
int totalRows = 0;
    String saveFile = "";
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        System.out.println("dddda  === \n " + in.toString());
        int formDataLength = request.getContentLength();
        pi_filesize = formDataLength / 1024;        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        saveFile = file.substring(file.indexOf("filename=\"") + 10);
        //System.out.println(saveFile + "\t 1" + file.toString());
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        // System.out.println(saveFile + "\t 2");
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
        // System.out.println(saveFile + "\t 3");
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1, contentType.length());
        int pos;
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
        // saveFile = "C:/" + saveFile;
        File f = new File(saveFile);
        FileOutputStream fileOut = new FileOutputStream(f);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();
/scripletI hope that will help you alot ...... any issue plz ask ............

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Now there is an other solution for you …. and i recommand you to use that ……

JSP NAME:

index.jsp

<html>
<head><title>Upload page</title></head></p> <p><body>
<form action=”employee_upload_profile_image.jsp” method=”post” enctype=”multipart/form-data” name=”form1″ id=”form1″>
<center>
<table border=”2″>
<tr>
<td align=”right”><b>Employee Name:</td>
<input type=”text” name=”emp_name”>
</tr>
<tr>
<td align=”right”><b>Employee Address:</td>
<input type=”text” name=”address1″>

</tr>
<tr>
<td>
</td>
<td>
<input type=”text” name=”address2″>
</td>
</tr>
<tr>
<td align=”right”><b>Contact Number:</td>
<input type=”text” name=”contact_number”>
</tr>
<tr>
<td align=”right”><b>Employee Email ID:</td>
<input type=”text” name=”email_id”>
</tr>

<tr>
<td align=”right”><b>Employee Image </td>
<td>
<input name=”file” type=”file” id=”file”>
<td>
</tr>

<tr>
<td align=”center”>
<input type=”submit” name=”Submit” value=”Submit”/>
<input type=”reset” name=”Reset” value=”Reset”/>

</td>
</tr>
</table>
</center>
</form>
</body>
</html>

=================================

JSP NAME:

employee_upload_profile_image.jsp

<%@ page import=”java.util.List” %>
<%@ page import=”java.util.Iterator” %>
<%@ page import=”java.io.File” %>
<%@ page import=”org.apache.commons.fileupload.servlet.ServletFileUpload”%>
<%@ page import=”org.apache.commons.fileupload.disk.DiskFileItemFactory”%>
<%@ page import=”org.apache.commons.fileupload.*”%>
<%@ page contentType=”text/html;charset=UTF-8″ language=”java” %>

<center><h1>Your  Profile has been Uploaded</h1></center>
<%    String emp_name = “”;
int count1 = 0;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
if (name.equals(“emp_name”)) {
emp_name = value;
count1 = 1;
}
} else {
try {
String itemName = item.getName();
File savedFile = new File(“D:/” + itemName);
item.write(savedFile);
if (count1 == 1) {
out.println(“<tr><td align=’left’><b>Name:</td><td><b>” + emp_name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
</td></tr></table></center>

and two jars

commons-fileupload-1.2.2.jar

commons-io-2.4.jar