Posts Tagged ‘jetty

25
Feb
11

MySQL Test Connection using Spring MVC

This page will describe how to create a spring MVC application to test a connection to MySQL database. The user will provide the connection URL and username/password. The system will make a simple connection to the database and return the results to the screen.

Note: This page was originally written in November 15 2009.

Requirements

  • Access to a MySQL Server
  • Maven 2
  • Eclipse
  • Spring 2.5
  • Java 1.5 or above

Start a new Project

Start a new project by creating it from an archetype.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp
Choose option:

Answer the questions like this:

Define value for groupId: : test
Define value for artifactId: : spring-mysql-test
Define value for version:  1.0-SNAPSHOT: :
Define value for package:  test: :
Confirm properties configuration:
groupId: test
artifactId: spring-mysql-test
version: 1.0-SNAPSHOT
package: test
 Y: :

cd spring-mysql-test
modify pom.xml and insert the following dependencies

	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring</artifactId>
		  <version>2.5.6</version>
		</dependency>
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-webmvc</artifactId>
		  <version>2.5.6</version>
		</dependency>
	<dependency>
		<groupId>org.apache.geronimo.specs</groupId>
		<artifactId>geronimo-servlet_2.5_spec</artifactId>
		<version>1.2</version>
		<type>jar</type>
		<scope>provided</scope>
	</dependency>
	</dependencies>

insert the following into

src/main/webapp/WEB-INF/web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>/app/helloWorld</welcome-file>
</welcome-file-list>

</web-app>

Insert the following into

src/main/webapp/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:p="http://www.springframework.org/schema/p" 
    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-2.5.xsd">

	<context:component-scan base-package="test" />

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

</beans>

Java Code

Before writing the Java files please create the following directory.

mkdir -p src/main/java/test

Create a java class that looks like this…
src/main/java/test/HelloWorldController.java

package test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.stereotype.Controller;

@Controller("/helloWorld")
public class HelloWorldController extends AbstractController {
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ModelAndView mav = null;
		// control logic goes here
		mav = new ModelAndView("helloWorld");
		return mav;
	}
}

mkdir -p src/main/webapp/WEB-INF/jsp

src/main/webapp/WEB-INF/jsp/helloWorld.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
	<head>
		<title>HelloWorld test page</title>
		<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
		<meta http-equiv="Content-Language" content="en-us" />
	</head>
	
	<body>
		Hello World page!
	</body>
</html>

Run the Project

In order to run the project we need to put a couple of more things into pom.xml file.

1. The jetty plugin will allow Maven to run the project in the jetty servlet container. In the plug-in section of the pom.xml file put in the following…
2. By default Maven uses an old version of the JDK to compile. We need to set it to use a higher version. (supports annotations). If you don’t have 1.6 then change the source and target elements below to 1.5 at least.

pom.xml inside the build tag

  <build>
    <finalName>spring-mysql-test</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.0.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.0.0.v20091005</version>
				<configuration>
					<scanIntervalSeconds>1</scanIntervalSeconds>
				</configuration>
			</plugin>
		</plugins>
  </build>

To run the web application type:
type

mvn jetty:run

Navigate your browser to http://localhost:8080/app/helloWorld to test if everything is okay up to this point. If something is not working please review the steps seen above and make sure you at least see hello world printed on the screen.

We will create a Controller that draws a input form that the user can use to specify database url, username, password.

src/main/java/test/DBParam.java

package test;

public class DBParam {
    public String url;
    public String username;
    public String password;
    
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

The controller will take this form submission and make a connection to the database with the results printed to the screen.

src/main/java/test/TestDBConnectionController.java

package test;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

@Controller("/dbParameters")
public class TestDBConnectionController extends SimpleFormController {

	public TestDBConnectionController() {
		setFormView("dbParameters");
		setCommandClass(DBParam.class);
		setSuccessView("success");
		setCommandName("dbParam");
	}

	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		System.out.println("form submitted");

		DBParam dbParam = (DBParam)command;
		String url = dbParam.getUrl();
		String username = dbParam.getUsername();
		String password = dbParam.getPassword();

		// make a connection
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection(url, username, password);
		System.out.println("got a connection: " + conn);

		return super.processFormSubmission(request, response, command, errors);
	}
}

We have enabled component scanning in our spring-servlet.xml file so we don’t have to register this controller in the xml file.

src/main/webapp/WEB-INF/jsp/dbParameters.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>DB Parameters</title>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="en-us" />

</head>
<body>
	<form method="post">
		<label>JDBC connect string: </label><input type="text" name="url" value="jdbc:mysql://hostname:3306/dbname" size="55"/><br/>
		<label>password: </label><input type="text" name="username"/><br/>
		<label>username: </label><input type="password" name="password"/><br/>
		<input type="submit" value="submit"/><br/>
	</form>
</body>
</html>

src/main/webapp/WEB-INF/jsp/success.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>DB Parameters</title>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="en-us" />

</head>
<body>
	success
</body>
</html>

Run the project

You may run the project under jetty

mvn jetty:run

navigate your browser to:

http://localhost:8080/app/dbParameters

Replace the URL with the url to your mysql database.

That’s it for now!!!

31
Jan
10

Restarting Jetty Automatically using scanTargets

This page describes the process of setting up jetty such that it will restart when resources are changed.

By default jetty only scans a limited set of directories for changes. If you change a jsp or property file chances are that the changes wont be registered. If you find this happening then try something like this in your maven pom.xml file.

<plugin>
	<groupId>org.mortbay.jetty</groupId>
	<artifactId>maven-jetty-plugin</artifactId>
	<configuration>
		<scanTargetPatterns>
			<scanTargetPattern>
				<directory>src/main/webapp</directory>
				<includes>
					<include>**/*</include>
				</includes>
			</scanTargetPattern>
		</scanTargetPatterns>
		<scanIntervalSeconds>2</scanIntervalSeconds>
	</configuration>
</plugin>

08
Nov
09

Create Web Project using Maven Archetypes

This page describes the process of creating a standard web project using maven Archetypes. Afterwards we will run the web application in the built-in servlet container called jetty and an external one with Tomcat 6.

Requirements

  1. Eclipse J2EE IDE
  2. Tomcat installed and integrated with eclipse WTP.
  3. Maven 2
  4. Ability to command line on your machine

We start by creating the project

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

By default the archetype does not create a javasource folder so go ahead and create the following directory under the project.

src/main/java

Also by default the web application is not a WTP application, it has no idea how to run itself under jetty and does not know how to regenerate itself as an eclipse project.

In order to make this project do all those cool things we need to add a couple lines of code in the plugins section of the pom.xml file.

                <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <configuration>
                                <warName>${artifactId}</warName>
                        </configuration>
                </plugin>
                <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-eclipse-plugin</artifactId>
                        <configuration>
                                <projectNameTemplate>${artifactId}</projectNameTemplate>
                                <wtpapplicationxml>true</wtpapplicationxml>
                                <downloadSources>true</downloadSources>
                                <downloadJavadocs>true</downloadJavadocs>
                                <wtpversion>1.5</wtpversion>
                                <classpathContainers>
                                        <classpathContainer>org.eclipse.jst.j2ee.internal.web.container</classpathContainer>
                                        <classpathContainer>org.eclipse.jst.j2ee.internal.module.container</classpathContainer>
                                </classpathContainers>
                        </configuration>
                </plugin>
                <plugin>
                        <groupId>org.mortbay.jetty</groupId>
                        <artifactId>jetty-maven-plugin</artifactId>
                                <version>7.0.0.v20091005</version>
                </plugin>

By default the pom.xml that is created by this archetype does not specify to the other plugins what jvm version we will be using: In the build section of the pom.xml file put the following.

        <pluginManagement>
                <plugins>
                        <plugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                </configuration>
                        </plugin>
                </plugins>
        </pluginManagement>

In order to create a web application you need additional dependencies to be added

<dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-servlet_2.5_spec</artifactId>
        <version>1.2</version>
        <type>jar</type>
        <scope>provided</scope>
</dependency>

Regenerate the eclipse project

mvn eclipse:clean eclipse:eclipse

Return to eclipse and refresh the project.

Creating a servlet

Create a test Servlet.

package com.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                System.out.println("servlet ran successfully");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        }

}

Modify the xml to look like this:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>TestServlet</servlet-name>
        <display-name>TestServlet</display-name>
        <description></description>
        <servlet-class>
        com.test.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>
</web-app>

Running the Web Project in Jetty

In the project top level directory start the jetty servlet engine.

mvn jetty:run

Open browser and navigate to http://localhost:8080/ You should be seeing a hello world page. To test the servlet navigate to http://localhost:8080/TestServlet

When you run the servlet you should see “servlet ran successfully” printed to the console and the same Hello World message in the browser.

When you are done with the test, shut down the jetty server by hitting CTRL-C on the command line window.

Running the Web Project in Tomcat 6

Please make sure you have shut-down jetty before proceeding… Unless you changed them both jetty and tomcat 6 run on the default port of 8080. They both can not run at the same time.

Using Eclipse WTP all you need to do is make sure that Tomcat is defined and you are able to start and stop it. Right click on the project and click “Run On Server” option. Tomcat should show some output on the terminal. Follow the same steps you did while testing jetty. You should get the same results as above.

Congratulations

You have just configured a simple web application project using archetypes and hosted the application using both the built in web-app server called jetty and Tomcat 6 under eclipse using WTP.

You can also try out the following post. This is a simpler way to start a Spring MVC application from an archetype.

Thats all for now!

This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.



Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 75 other followers

April 2017
S M T W T F S
« Mar    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Blog Stats

  • 807,309 hits