Link to home
Start Free TrialLog in
Avatar of Errang Genevre
Errang Genevre

asked on

How to build a Spring MVC application?

Hello,

I'm just starting out with Spring and I'm trying to build a web application.

At this point, I'm trying to get a simple web page to show up and figure out how to map the web pages to controllers; I've been through numerous websites, but I'm having problems getting them to properly deploy on the Tomcat server, I haven't worked much with Tomcat either and have very basic knowledge of it.

I've even tried using the example code from the Spring in Action book; but I believe I'm having problems with Maven and Tomcat.

I would really appreciate any tutorials detailing the finer points of setting up Maven, Tomcat and a basic "Hello, world!" example of a Spring MVC application to get me started.

Thanks in advance!
Avatar of mccarl
mccarl
Flag of Australia image

I would really appreciate any tutorials detailing the finer points of setting up Maven, Tomcat and a basic "Hello, world!" example of a Spring MVC application to get me started.
Most of the tutorials that I have seen (and so I'm guessing are the same ones that you have tried) and already pretty much as "fine" as they get. I don't think that anything that we would do would be much different.

So, what to do then??? I would recommend a few things...

Use an IDE that it closely aligned with what you are doing, such as Spring Tool Suite or at least Eclipse, and recent versions of such. They have most of the moving parts already setup for you. You may already have this but you haven't made mention above
Take one step at a time! If you don't have much knowledge in any of Maven, Tomcat, and Spring, then you are just asking for trouble in trying something that utilises all three at the same time. When you have problems, you won't know where to look. So start with some very simple, basic Maven tutorials that deal in plain old Java first. Only once you have  a good idea of what is happening, then look at a basic Tomcat project. After that, then you can look at Spring too and linking it all together.
Since, as I said above, I don't think anyone here would be able to write anything different from the tutorials that are already out there, the main way that we could help is if you ask specific questions of the problems that you are facing (with ALL the relevant information, error messages, etc, etc) and we can work through your issues with you.
Avatar of Errang Genevre
Errang Genevre

ASKER

>> Use an IDE that it closely aligned with what you are doing, such as Spring Tool Suite or at least Eclipse,

I'm using IntelliJ

>> Take one step at a time! If you don't have much knowledge in any of Maven, Tomcat, and Spring, then you are just asking for trouble in trying something that utilises all three at the same time.

Well, I am able to get it to build successfully, and I have tested out how to deploy web pages in Tomcat; so I'm reasonably sure that my problem lies with Spring.

>> Since, as I said above, I don't think anyone here would be able to write anything different from the tutorials that are already out there, the main way that we could help is if you ask specific questions of

Well, actually I was able to fix the errors; here's what I have so far:

My java controller
package springmvc.web;

import java.io.IOException;

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

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

public class HelloWorldController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws ServletException, IOException {

        String aMessage = "Hello World MVC!";

        ModelAndView modelAndView = new ModelAndView("hello_world");
        modelAndView.addObject("message", aMessage);

        return modelAndView;
    }
}

Open in new window


My view
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<p>This is my message: ${message}</p>
</body>
</html>

Open in new window


My springmvc-servlet (I'm not entirely sure what this is for):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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-2.5.xsd">

    <bean name="/hello_world.html" class="springmvc.web.HelloWorldController"/>

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

</beans>

Open in new window


My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>
            jsp/hello_world.jsp
        </welcome-file>
    </welcome-file-list>

</web-app>

Open in new window


Everything seems to be running properly...
/Downloads/apache-tomcat-8.0.14/bin/catalina.sh run
[2014-10-13 12:16:35,912] Artifact SpringMVC:war exploded: Server is not connected. Deploy is not available.
13-Oct-2014 00:16:36.094 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/8.0.14
13-Oct-2014 00:16:36.095 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:   Sep 24 2014 09:01:51
13-Oct-2014 00:16:36.095 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:  8.0.14.0
13-Oct-2014 00:16:36.096 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:        Mac OS X
13-Oct-2014 00:16:36.096 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:     10.9.5
13-Oct-2014 00:16:36.096 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:   x86_64
13-Oct-2014 00:16:36.096 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:    1.8.0_05-b13
13-Oct-2014 00:16:36.096 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:     Oracle Corporation
13-Oct-2014 00:16:36.203 INFO [main] org.apache.catalina.core.AprLifecycleListener.init The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/sudheendraayalasomayajula/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
13-Oct-2014 00:16:36.348 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
13-Oct-2014 00:16:36.359 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
13-Oct-2014 00:16:36.361 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
13-Oct-2014 00:16:36.362 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
13-Oct-2014 00:16:36.363 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 322 ms
13-Oct-2014 00:16:36.382 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
13-Oct-2014 00:16:36.382 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.14
13-Oct-2014 00:16:36.388 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
13-Oct-2014 00:16:36.394 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
13-Oct-2014 00:16:36.394 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 31 ms
Connected to server
[2014-10-13 12:16:36,401] Artifact SpringMVC:war exploded: Artifact is being deployed, please wait...
13-Oct-2014 00:16:37.112 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.FrameworkServlet.initServletBean FrameworkServlet 'springmvc': initialization started
13-Oct-2014 00:16:37.135 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.context.support.AbstractApplicationContext.prepareRefresh Refreshing WebApplicationContext for namespace 'springmvc-servlet': startup date [Mon Oct 13 00:16:37 EDT 2014]; root of context hierarchy
13-Oct-2014 00:16:37.167 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions Loading XML bean definitions from ServletContext resource [/WEB-INF/springmvc-servlet.xml]
13-Oct-2014 00:16:37.261 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@226d8ce8: defining beans [/hello_world.html,viewResolver]; root of factory hierarchy
13-Oct-2014 00:16:37.323 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler Mapped URL path [/hello_world.html] onto handler '/hello_world.html'
13-Oct-2014 00:16:37.404 INFO [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.FrameworkServlet.initServletBean FrameworkServlet 'springmvc': initialization completed in 291 ms
[2014-10-13 12:16:37,417] Artifact SpringMVC:war exploded: Artifact is deployed successfully
[2014-10-13 12:16:37,417] Artifact SpringMVC:war exploded: Deploy took 1,016 milliseconds
13-Oct-2014 00:16:46.390 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /Users/sudheendraayalasomayajula/Downloads/apache-tomcat-8.0.14/webapps/manager
13-Oct-2014 00:16:46.412 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /Users/sudheendraayalasomayajula/Downloads/apache-tomcat-8.0.14/webapps/manager has finished in 21 ms

Open in new window


But I get a 404 error, saying the resource is not available.
But I get a 404 error, saying the resource is not available.

What URL are you navigating too? A common error is that your webapp has been deployed under a certain context. ie. instead of navigating too..

http://servername:8080/hello_world.html

You need...

http://servername:8080/contextname/hello-world.html

Unfortunately, nothing in your code or logs above, can give me a hint as to what "contextname" should be but it is generally the name of your project. I have noticed that the tomcat "manager" app is also being deployed (last 2 lines of the logs) and so you should be able to navigate to http://servername:8080/manager to see all the contexts that are loaded and running. Also, if you can find the right "webapps" directory that is being used (there can be multiple depending on the way Tomcat has been started), the context will have the same name as the directory in your "webapps" directory (it may be this one.... /Users/sudheendraayalasomayajula/Downloads/apache-tomcat-8.0.14/webapps)
I haven't founnd anything in the tomcat directory; but thanks for pointing out the issue with the context name, I'm looking into other tutorials that implement it (the project name thing didn't work for me).

Also, could you please suggest a good Maven application and a Tomcat application that would provide a foundation?
Alright, I'm 90% sure that Tomcat is what's messing things up for me... I tried deploying the war on this site:

http://javabeginnerstutorial.com/spring-framework-tutorial/developing-a-spring-3-framework-mvc-application-step-by-step-tutorial/

It shows up on their site: http://javabeginnerstutorial.appspot.com/insertJdbcContact.do

But I can't get it to run on localhost. I tried both Tomcat 7 & 8.
SOLUTION
Avatar of Robert Scully
Robert Scully

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried deploying the war on this site:
Just so that we are on the same page, when you say that you deployed this (or any of the other attempts at getting something working), are you using any built features of IntelliJ to do this, or are you just placing the .war file into the webapps directory of Tomcat?

If you can give me a bit more information about exactly what you are doing and what happens, we should be able to help further. (ie. if you can provide maybe some screenshots of what you are doing or otherwise, some very detailed description of what you are doing)  Unfortunately, it is just that there are a number of ways that this can be done, and a number of variables (including IntelliJ which I don't have experience using) so it is hard to just say, "Do this, do that, and it will work"
@Robert Scully >> Have you read the spring MVC documentation on the spring website? I strongly suggest completing the Spring MVC tutorial before you continue onto anything else. It will give you the general idea:

I started with http://docs.spring.io/docs/Spring-MVC-step-by-step/; but I had the same problem with deploying to Tomcat, so I figured that tutorial might be outdated since it was using Spring 3.x. Let me try out the tutorial you pointed out.

@Robert Scully >> Also, when you build the WAR file, are you building it on Spring STS? You should build it on STS and deploy it on the inbuild pivotal tcserver.

Let me try STS too.

@Robert Scully >> Also, if you're running on the local host and it isn't working, have you checked if there are any firewalls which may be causing this problem?

My firewall is turned off

@mccarl >> Just so that we are on the same page, when you say that you deployed this (or any of the other attempts at getting something working), are you using any built features of IntelliJ to do this, or are you just placing the .war file into the webapps directory of Tomcat?

Since I downloaded the war file from the site, I placed the war file directly within webapps/ROOT directory.

The only thing I changed within Tomcat is adding these lines in conf/tomcat-users.xml:
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

Open in new window


I've constantly been getting this error with IntelliJ:
Unable to ping server at 1099. (This is the JMX port in the Tomcat configuration)

I'm not entirely sure why I get that; a little messing around gets me out of that error, but I'm not entirely sure what I did to fix it.

But in order to run this war file, I just started Tomcat's server by executing:

Tomcat/bin/catalina.sh run

After I verified that the basic Tomcat homepage was available; I went ahead and put the war file in the Tomcat/webapps/ROOT directory (where I saw the resources for Tomcat's home page).

After that, I substituted http://javabeginnerstutorial.appspot.com/insertJdbcContact.do with http://localhost/insertJdbcContact.do
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ah... that makes me feel stupid.

Now I'm getting this error: HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception

But I think I have a better chance at getting it to work.

Thanks for all the help!
Not a problem, glad to help!