Creating a Maven web application and integration for Eclipse and IntelliJ IDEs

Reading Time: 1 minute

Hi folk

In this tutorial I will show you how you can create a dynamic web project using maven in command line. First of all if you would like to create a web app rapidly then issue the command below, or if you would like to create and browse different type of projects remove the project type and other specifications in the below given command. On Linux, Windows or Mac does not matter launch your terminal/command line app to create our project:

mvn archetype:generate -DgroupId=PROJECTPACKINGNAMEGOESHERE -DartifactId=PROJECTNAMEGOESHERE -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

As soon as you launch this code the outcome should look like this:

Selection_016

our project is ready and lets convert our project into an Eclipse or IntelliJ project issue the command below but first of all navigate to the project folder first otherwise you will have the errors maven unable to locate the pom.xml file:

Eclipse Integration

mvn eclipse:eclipse -Dwtpversion=2.0

IntelliJ Integration

mvn idea:idea -Dwtpversion=2.0

After the command our project will look and converted to that IDE structure, the below the folder structure since I am an IntelliJ fan the here is my folder output:

Selection_017

Deploying Maven Projects to Tomcat

Reading Time: 2 minutes

In this tutorial I will show you how to easily deploy your project on your favorite. We have a few of code and file changes thats all. First of all lets start out with the pom file. We need maven tomcat plugin to deploy our war file, copy and paste the below code between build tags in your pom.xml file and edit it the way you want

<plugins>  
    <!-- this maven plugin directly does deploy the project to tomcat7 -->
    <!-- also check out tomcat users and maven settings for the equality of credentials -->
    <!-- if credentials do not match maven will fail to deploy the project to AS -->
          <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.1</version>
              <configuration>
                  <url>http://localhost:8080/manager/text</url>
                  <!-- Refer to the server settings in your ~/.m2/settings.xml -->
                  <server>dev-tomcat</server>
                  <path>/PROJECTNAME</path>
              </configuration>
          </plugin>
            <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-compiler-plugin</artifactId>  
                <version>3.0</version>  
                <configuration>  
                    <source>${jdk.version}</source>  
                    <target>${jdk.version}</target>  
                </configuration>  
            </plugin>  
        </plugins>

We now need to alter our tomcat-users.xml file which is located under conf folder in your main tomcat file. Add the line below in your tomcat-users.xml file

<tomcat-users>
 <role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <role rolename="admin-gui"/>
 <role rolename="admin-script"/>

 <user username="tomcat" password="password"  roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>
</tomcat-users>

And now one more file left to be altered, settings.xml file once again located in conf folder in your main maven folder. Add this line between servers tag

<server>
   <id>dev-tomcat</id>
   <username>tomcat</username>
   <password>password</password>
  </server>

We are all setup right now. To give you the advice if you are working on STS or Eclipse you will need to add m2e plugin from eclipse market to run the desired project with the goal

mvn clean tomcat7:deploy

If you redeploy it please do not forget to change the goal. If your favorite IDE is IntelliJ then it is still easy. Expand Maven Projects side on the right(If you cant find it navigate to View > Tool Buttons) and go to Plugins expand tomcat7 and click on tomcat7:deploy

After these settings navigate to your serverpath/projectname to see all works.

Spring Security Login Example

Reading Time: 2 minutes

In this tutorial we are covering full of spring security login example but with no database connection. With following tutorials I am thinking to add one with database. To understand basic spring security you may study this example. In this tutorial I used maven and you will find the pom.xml file as well and my favorite IDE IntelliJ. Let us get started with the project

Directory Structure

Selection_015

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>SpringSecurityFormApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringSecurityFormApp Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <properties>
        <jdk.version>1.7</jdk.version>
    </properties>
  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>

      <!-- Spring Security -->
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-core</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-web</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-config</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <!-- JSTL Dependancy -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringSecurityFormApp</finalName>
      <plugins>
          <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.1</version>
              <configuration>
                  <url>http://localhost:8080/manager/text</url>
                  <server>mytomcat</server>
                  <path>/SpringSecurityFormApp</path>
              </configuration>
          </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.0</version>
              <configuration>
                  <source>${jdk.version}</source>
                  <target>${jdk.version}</target>
              </configuration>
          </plugin>
      </plugins>
  </build>
</project>

index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

loginForm.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>spring security form login demo</title>
</head>
<body>
<table>
    <tr>
        <td valign="top"><c:if test="${not empty param.login_error}">
            <font color="red"> Invalid user name or password, try again.
                <br /><br />
            </font>
        </c:if>
            <form name="login_form"
                  action="<c:url value='j_spring_security_check'/>" method="POST">
                <div>
                    <table width="40%" border="0" cellpadding="0" cellspacing="0">
                        <tr>
                            <td valign="top">
                                <table border="0" cellspacing="0" cellpadding="4" width="40%">
                                    <tr>
                                        <td colspan="2">Custom Login Form
                                            <hr width="100%" size="1" noshade align="left">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td width="80">Username</td>
                                        <td valign="top" align="left">
                                            <input type='text'
                                                   id='username'
                                                   name='j_username'
                                                   value='<c:if test="${not empty param.login_error}">
                                                     <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/>
                                                   </c:if>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td width="80">Password</td>
                                        <td valign="top" align="left"><input type='password'
                                                                             name='j_password' size="30" maxlength="30"></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td><input type="submit" value="Submit" /></td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
            </form></td>
    </tr>
</table>
</body>
</html>

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/j2ee/web-app_2_4.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
            http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <display-name>SpringSecurityDemo</display-name>
    <description>SpringSecurityDemo</description>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml,
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
            org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

    <http auto-config="true">
        <intercept-url pattern="/loginForm.jsp" filters="none"/>
        <intercept-url pattern="/**" access="ROLE_USER" />
        <form-login login-page="/loginForm.jsp"
                    default-target-url="/login.do" always-use-default-target="true"
                    authentication-failure-url="/loginForm.jsp?login_error=1" />
        <logout logout-success-url="/loginForm.jsp" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="tugrul" password="12345"
                      authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

dispatcher-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.example.controller" />
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Message : ${message}</h1>   
<a href="<c:url value="/j_spring_security_logout" />" > Logout</a>
</body>
</html>

WelcomeController.java

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {
    @RequestMapping(value="/login.do", method = RequestMethod.GET)
    public ModelAndView printWelcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "Spring security allows you");
        modelAndView.setViewName("login");
        return modelAndView;
    }
}

You may now deploy the application to the server and test it

 

Spring 3 MVC Hello World Example

Reading Time: 2 minutes

In this simple tutorial I will show you how to create the folder structure, add necessary libraries and write code of Spring 3 MVC. First off all your project has to have the following jars to be imported in your project minimum:

  • antlr-2.7.6.jar
  • commons-lang-2.4.jar
  • commons-logging-1.1.1.jar
  • jstl.jar
  • log4j-1.2.11.jar
  • org.springframework.beans-3.0.6.RELEASE.jar
  • org.springframework.context-3.0.6.RELEASE.jar
  • org.springframework.core-3.0.6.RELEASE.jar
  • org.springframework.expression-3.0.6.RELEASE.jar
  • org.springframework.web-3.0.6.RELEASE.jar
  • org.springframework.web.servlet-3.0.6.RELEASE.jar

This is here how your project folder needs to look like:

Spring3MVCProjectLayout

Add these necessary jars into lib folder, to do it please drag them into the folder so that you won’t have to kill yourself how to. Prohibit yourself from adding the jars as classpath.

So let’s get our hands into codes, section by section I will be giving you the explanations what all the files mean and stand for. First of all create a Dynamic web project with a name called “Spring3MVC” or the way you want. Second of all drag the necessary jars into lib folder and let us get started with the code. First of all create a new folder called “jsp” right under “WEB-INF” folder.

Right click on the project and create a new class called “HelloWorldController.java” and type the package as “com.example.controller”, the below the code comes:

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

    @RequestMapping("/hello")
    public ModelAndView helloWorld() {

        String message = "Hello World, this is Spring 3.0 MVC!";
        return new ModelAndView("hello", "message", message);
    }
}

This is our controller code, this will be residing in Java Resources src folder which is where it is supposed to be, so let’s move on and create a our jsp files. Right click on the project and create a new jsp file called “index.jsp” under “WebContent” please be aware this index file should not be in “jsp” folder, and paste this code into the file

<html>
<head>
    <title>Spring 3.0 MVC Hello World Sample</title>
</head>
<body>
    <a href="hello.html">Say Hello</a>
</body>
</html>

and now the same way create a new folder in “jsp” folder called “hello.jsp” and paste the code below

<html>
<head>
    <title>Spring 3.0 MVC Hello World Sample</title>
</head>
<body>
    ${message}
</body>
</html>

Its time to create our configuration files which will be in charge of managing our project. First of all let us create the “web.xml” file under “WEB-INF” folder and paste the code below

<?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</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <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>

and now only one file left to be created our spring configuration file called “spring-servlet.xml” please create this folder the same way right underneath the folder “WEB-INF” and paste this code

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd     
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan
        base-package="com.example.controller" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

and now we are pretty much ready to deploy the code to our application server. Please go ahead and give it a shot, and I will below be explaining what these files stand for we newly created.

You can download the full project here Spring3MVC

Installing LAMP stack on Ubuntu

Reading Time: 1 minute

When we work on Ubuntu in case of need of LAMP stack we programmers always take the hard way to individually install, setup and configure components like Apache PHP MySQL. One of the greatest things with Ubuntu is that we are able to install LAMP stack with one command line!!! So let us get started towards the procedure/

First of all update your system

sudo apt-get update && sudo apt-get upgrade

Here is the command line comes, the below execute the command and lie back wait till all of necessary packages are downloaded installed and well configured

sudo apt-get install lamp-server^

During the installation you will be asked to set up the root password for MySQL, enter your credentials and let Ubuntu configure the rest for you. After all you will have Apache, MySQL and PHP installed and configured on your Ubuntu

Installing and configuring JRE on Ubuntu

Reading Time: 2 minutes

On your keyboard press on CTRL+ALT+T to reach terminal screen, first of all we will purge open jdk on ubuntu, to achieve this please execute the command below

sudo apt-get purge openjdk*

When we purge the open jdk we can now navigate to Oracle’s official web site to obtain the JRE package. The link could be outdated you may use Google instead.

http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html

The never versions may come up, please be aware as long as you are using the 7th version, update versions may change, you can keep it uptodate. We need the Linux packages and the “tar.gz” compression type as well. I am running an x64 architecture version of Ubuntu, if you are on x32 then choose that architecture type.

When we are all good with the download switch to the terminal screen and navigate to the folder where you’ve downloaded the JRE package. First of all we will need to unpack the file, please execute the command below:

tar -zxvf jre-7u45-linux-x64.tar.gz

type the “ls -a” command to make sure the package has been decompressed perfectly. To move on, we need to make the new folder for JRE. I am picking a general-use-location for keeping the software you may want to keep it in a different location. Execute the command to create the folder

sudo mkdir -p /usr/lib/jvm/jre1.7.0

and then migrate all the files and folders we have uncompressed:

sudo mv jre1.7.0_45/* /usr/lib/jvm/jre1.7.0/

we now need to execute the below command to meet ubuntu with JRE:

sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jre1.7.0/bin/java 0

We are now all setup, there is one more point i would like to go further is that if you are using Firefox, to set JRE up for the browser execute the below command to make a new folder for the plugin

mkdir ~/.mozilla/plugins

and we need to link the file to the newly created folder there are 2 differences for x32 and x64 architectures, i am separately giving the commands

x32:

ln -s /usr/lib/jvm/jre1.7.0/lib/i386/libnpjp2.so ~/.mozilla/plugins/

x64

ln -s /usr/lib/jvm/jre1.7.0/lib/amd64/libnpjp2.so ~/.mozilla/plugins/

To test and validate our JRE installation you may browse this link http://www.java.com/en/download/installed.jsp to find out about the installation