Spring MVC Controller is not called -but compiling process seems fine - java

I tried to create a little Java-web-project, while using Spring MVC Framework.
To build my project, I use ant.
The compiling process seems to work, but unfortunately my controller class( and method) is never been called.
Here are my solution files.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>HelpMe</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/test/</url-pattern>
</servlet-mapping>
</web-app>
mvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.please.help.me" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller-class:
package com.please.help.me;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class WelcomeController {
#RequestMapping("/page1")
public String showWelcomePage1() {
System.out.println("show page 1...");
return "page1";
}
#RequestMapping("/page2")
public String showWelcomePage2() {
System.out.println("show page 2...");
return "page2";
}
}
ant-build-file: (build.xml)
<project name="HelpMeProject" default="compile" basedir="." xmlns:ivy="antlib:org.apache.ivy.ant">
<description>
Build file for not working project
</description>
<!-- set global properties for this build -->
<property name="src" location="src" />
<property name="build" location="build" />
<property name="lib" location="lib" />
<property name="classes" location="${build}\WEB-INF\classes" />
<path id="project-classpath">
<fileset dir="${build}\WEB-INF\lib" includes="*.jar" />
<fileset dir="${src}" />
</path>
<target name="compile" description="compile the source" >
<delete dir="${lib}" />
<delete dir="${build}" />
<mkdir dir="${lib}" />
<!-- Do ivy retrieve -->
<ivy:retrieve pattern="${lib}/[type]/[artifact]-[revision].[ext]" />
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}" />
<mkdir dir="${build}\WEB-INF\lib" />
<mkdir dir="${classes}" />
<copy todir="${build}\WEB-INF\lib">
<fileset dir="${lib}\jar" />
<fileset dir="${lib}\bundle" />
</copy>
<copy todir="${build}">
<fileset dir="web" />
</copy>
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${classes}" classpathref="project-classpath" debug="true" />
</target>
</project>
and finally my tomcat deployment descriptor: (helpme.xml)
<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" docBase="c:\..myPath..\HelpMe\build\" path="/helpme">
</Context>
After running the compile-ant-script, everything seems fine. Tomcat starts as it should do, but it doesn't matter which URL I call -the controller won't be touched.
This is what I tried:
localhost:8080/
localhost:8080/test
localhost:8080/test/page1
localhost:8080/page1
I looked for similiar topics, but did not find an solution for that problem. Maybe you can help me.
Thanks a lot.

In your case if you have any request mapping as /test/ in controller then
localhost:8080/test/
it will will work.
If you want any url after /test/ needs to be work like :
localhost:8080/test/page1
you need to map it in web.xml as :
/test/*
as I commented.
in url /test/*, the * means any thing after /test/

Change
<url-pattern>/test/</url-pattern>
to
<url-pattern>/</url-pattern>
then localhost:8080/page1 at least should work fine
is this a maven project? If so you can you show us the pom.xml ?
Most people start their webapp with Requestmapping "/"
If you want a quick start to Spring MVC Programming no junk or setup use STS (spring tools suite) although someone gave me a hard time because I like the tool saying it came with a pre-setup tomcat therefore lessening the experience while that is true but eventually you will need to near how to deploy manually to tomcat anyway.

Related

Arquillian and wildfly 10 - Cannot undeploy: 144976d2-382b-438f-8b8a-2007db7b53c2.war

I'm running integration tests from MVN with Wildfly 10 and Arquilliain. I get the following error:
WARN ArchiveDeployer - Cannot undeploy:
144976d2-382b-438f-8b8a-2007db7b53c2.war
org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper$ServerDeploymentException:
java.lang.Exception: "WFLYCTL0216: Management resource
'[(\"deployment\" => \"144976d2-382b-438f-8b8a-2007db7b53c2.war\")]'
not found" at
org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper.undeploy(ServerDeploymentHelper.java:114)
at
org.jboss.as.arquillian.container.ArchiveDeployer.undeploy(ArchiveDeployer.java:55)
at
org.jboss.as.arquillian.container.CommonDeployableContainer.undeploy(CommonDeployableContainer.java:152)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController$4.call(ContainerDeployController.java:205)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController$4.call(ContainerDeployController.java:185)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
Here's my Arquillian (identical to another project that works, so I don't think this is the issue, all the ports are right):
<?xml version="1.0" ?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://jboss.org/schema/arquillian"
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<engine>
<property name="deploymentExportPath">target</property>
</engine>
<!--
<container qualifier="wildfly-managed" default="true">
<configuration>
<!– <property name="serverConfig">standalone.xml</property> Does not work, use -DjbossHome=.....–>
<property name="outputToConsole">true</property>
<property name="javaVmArguments">-Djboss.socket.binding.port-offset=100</property>
<property name="managementPort">10090</property>
</configuration>
</container>
-->
<container qualifier="wildfly-remote" default="true">
<protocol type="Servlet 3.0">
<property name="host">192.168.3.70</property>
<property name="port">8180</property>
</protocol>
<configuration>
<property name="managementPort">10090</property>
<property name="username">mike</property>
<property name="password">mike</property>
<property name="managementAddress">192.168.3.70</property>
</configuration>
</container>
<extension qualifier="transaction">
<property name="manager">java:jboss/UserTransaction</property>
</extension>
</arquillian>
My deployment is built like so:
#Deployment
public static WebArchive createDeployment() {
WebArchive wa = ShrinkWrap.create(WebArchive.class).addPackage(Baby.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource("jboss-deployment-structure.xml", "jboss-deployment-structure.xml")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsResource("arquillian.xml", "arquillian.xml").addAsResource("log4j.xml", "log4j.xml")
.addAsLibrary(Maven.resolver().loadPomFromFile("pom.xml").resolve("joda-time:joda-time:2.9.3")
.withTransitivity().asSingleFile())
.addAsLibraries((Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:2.7.4").withTransitivity()
.asFile()));
The app works fine, and if I launch it as a managed container on a local WF installation it works. For some reason, the remote container is failing.
Any ideas?
EDIT:
I also added this to web.xml and it did not change the issue:
<context-param>
<param-name>antiJARLocking</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>antiResourceLocking</param-name>
<param-value>true</param-value>
</context-param>

How to ignore "id" in Short Variable rule using PMD

I am using PMD plugin (version 4.0.2) for Eclipse (Eclipse Kepler Java EE). I have configured a naming rule: ShortVariable.
This works fine except for parameters like "id" and "e". I want PMD to ignore these. So I searched for a way to ignore certain parameters. I found this link (although it's for phpmd) and tried it, yet I can't seem to get it working. My config file looks like this (XML):
<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
My PMD
</description>
<rule ref="rulesets/java/naming.xml/ShortVariable">
<property name="exceptions" value="id" />
</rule>
</ruleset>
When I try to import this ruleset using the eclipse plugin, it shows no possible rules to import.
Any ideas?
I found a solution to my problem here.
The resulting xml looks like this:
<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
My PMD
</description>
<rule ref="rulesets/java/naming.xml/ShortVariable">
<properties>
<property name="xpath">
<value>
//VariableDeclaratorId[(string-length(#Image) < 3) and (not (#Image='id'))]
[not(ancestor::ForInit)]
[not((ancestor::FormalParameter) and (ancestor::TryStatement))]
</value>
</property>
</properties>
</rule>
</ruleset>
To be able to ignore more variable names, repeat the following part:
and (not (#Image='myVariableToIgnore'))
The folowing XML is valid for PHP tool PHPMD 2.2.3
<?xml version="1.0"?>
<!DOCTYPE ruleset>
<ruleset
name="My PMD ruleset for symfony 2.5"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"
>
<rule ref="rulesets/unusedcode.xml" />
<rule ref="rulesets/codesize.xml" />
<rule ref="rulesets/cleancode.xml" />
<rule ref="rulesets/controversial.xml" />
<rule ref="rulesets/design.xml" />
<rule ref="rulesets/naming.xml">
<exclude name="ShortVariable" />
</rule>
<rule ref="rulesets/naming.xml/ShortVariable">
<properties>
<property name="exceptions" value="id,em" />
</properties>
</rule>
</ruleset>
Update xml
<rule ref="category/java/codestyle.xml/ShortVariable">
<properties>
<property name="xpath">
<value>
//VariableDeclaratorId[(string-length(#Image) < 3) and (not (#Name='id'))]
[not(ancestor::ForInit)]
[not((ancestor::FormalParameter) and (ancestor::TryStatement))]
</value>
</property>
</properties>
</rule>

Spring/Mule schema issue

I am experiencing the following exception when launching my mule application:
SEVERE: Line 6 in XML document from mule-spring-config.xml is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 41; cvc-elt.1: Cannot find the declaration of element 'beans'. (org.mule.api.lifecycle.InitialisationException)
org.mule.api.config.ConfigurationException: Line 6 in XML document from mule-spring-config.xml is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 41; cvc-elt.1: Cannot find the declaration of element 'beans'. (org.mule.api.lifecycle.InitialisationException)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:52)
at org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at org.mule.context.DefaultMuleContextFactory.createMuleContext(DefaultMuleContextFactory.java:97)
at org.mule.config.builders.MuleXmlBuilderContextListener.createMuleContext(MuleXmlBuilderContextListener.java:169)
at org.mule.config.builders.MuleXmlBuilderContextListener.initialize(MuleXmlBuilderContextListener.java:98)
at org.mule.config.builders.MuleXmlBuilderContextListener.contextInitialized(MuleXmlBuilderContextListener.java:74)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
The following XML is the start of my mule xml configuration file. The schema for spring beans is obviously specified. What is even worst is that the exact same header works for another similar application. Does anyone have a clue what could be the problem here?
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xmlns:jersey="http://www.mulesoft.org/schema/mule/jersey"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/jersey http://www.mulesoft.org/schema/mule/jersey/current/mule-jersey.xsd
http://jersey.apache.org/core http://jersey.apache.org/schemas/core.xsd">
<endpoint name="REST" address="http://localhost:8082/system" />
<!-- Otds connector -->
<spring:bean id="tokenProvider"
class="com.is.TokenProvider">
<spring:property name="location"
value="http://sampleLocation.com" />
</spring:bean>
<spring:bean id="credentialStoreClient"
class="com.is.CredentialStoreClient">
<!-- Integration services protocol -->
<spring:constructor-arg index="0"
type="java.lang.String" value="http" />
<!-- Integration services host -->
<spring:constructor-arg index="1"
type="java.lang.String" value="sample.com" />
<!-- Integration services port -->
<spring:constructor-arg index="2"
type="java.lang.String" value="8080" />
<!-- Integration services context -->
<spring:constructor-arg index="3"
type="java.lang.String" value="/server" />
</spring:bean>
<!-- Authentication provider web service class -->
<spring:bean id="authenticationProvider"
class="com.api.system.AuthenticationProvider">
<spring:property name="tokenProvider"
ref="tokenProvider" />
<spring:property name="credentialStoreClient" ref="credentialStoreClient" />
</spring:bean>
<flow name="API">
<inbound-endpoint ref="REST" />
<jersey:resources>
<component class="com.api.system.VersionSender" />
<component>
<spring-object bean="authenticationProvider" />
</component>
</jersey:resources>
</flow>
</mule>
Maybe this will help it was all working before I changed the package name of the VersionSender and Authentication provider classes from admin to system!
EDIT
Web.xml the api-config.xml is the mule configuration file above.
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<context-param>
<param-name>org.mule.config</param-name>
<param-value>api-config.xml</param-value>
</context-param>
<!-- To use a Mule XML configuration file use this context listener -->
<listener>
<listener-class>org.mule.config.builders.MuleXmlBuilderContextListener</listener-class>
</listener>
</web-app>
Check the dependencies that get embedded in the WEB-INF/lib directory of your web application: the versions of the Spring JARs must all be 3.1.1.RELEASE for Mule 3.3.0. Also ensure that you are actually embedding the Spring Beans JAR itself.

appengine-web.xml - XML error validating

when I try to deploy my App Engine Project, the following Valditation Error is shown:
An internal error occurred during: "Deploying Guestbook to Google".
XML error validating C:\Users\Adrian\workspace\Guestbook\war\WEB-INF\appengine-web.xml against C:\eclipse\plugins\com.google.appengine.eclipse.sdkbundle_1.5.0.r36v201105092302\appengine-java-sdk-1.5.0\docs\appengine-web.xsd
Here is my appengine-web.xml:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>adrianschaeferandroid</application>
<version>1</version>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
</system-properties>
<static-files>
<include path="/favicon.ico" />
</static-files>
<static-files>
<include path="stylesheets/main.css" />
</static-files>
</appengine-web-app>
Can anyone see the Validation Error? Shall I post the appengine-web.xsd?
you can only have 1 static-files element. if you have multiple include, you should nest them all within a static-files element.
thus the correct appengine-web.xml should be:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>adrianschaeferandroid</application>
<version>1</version>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
</system-properties>
<static-files>
<include path="/favicon.ico" />
<include path="stylesheets/main.css" />
</static-files>
</appengine-web-app>
You will find it a lot easier to not make such errors if you configure your app GAE/Java app using an app.yaml file to generate both the web.xml and appengine-web.xml: https://developers.google.com/appengine/docs/java/configyaml/appconfig_yaml

Spring mvc controller issue

I'm trying to learn spring MVC, so far so good but I'm kind of stuck now. I'm trying to learn how to create json and get it with javascript(jquery).
But for testing purposes I tried to create something just so I can see that is displayed properly trough http request, then I'll try to create json and get it, but so far I can't even get the request to work. Here is my controller :
#Controller
#RequestMapping(value="/")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
Map<Long,Item> itemMap = createItemMap();
#RequestMapping(value="item/{itemId}", method=RequestMethod.GET)
public #ResponseBody Item get(#PathVariable Long itemId) {
Item item = itemMap.get(itemId);
if (status == null) {
throw new ResourceNotFoundException(itemId);
}
return item;
}
private Map<Long,Item> createItemMap(){
//omitted because its irrelevant
//I created 2 item objects , with id 1 and 2 for testing purposes
}
}
This is content of my servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Imports user-defined #Controller beans that process client requests -->
<beans:import resource="controllers.xml" />
</beans:beans>
And controllers.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<context:component-scan base-package="com.testing.mvc.controller" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
</beans>
My war is called Test.war, when I try localhost:8080/Test I get index view which is OK. But regardless of what I try:
localhost:8080/Test/item/1
localhost:8080/Test/item?itemId=1
localhost:8080/item?itemId=1
I end up with some kind of error, the most interesting is this one :
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
I've googled alot found these to be interesting :
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/
Mapping restful ajax requests to spring
Spring's Json not being resolved with appropriate response
Nothing helped so far, any idea what I'm missing. Sorry for providing too much info.
As far as I can tell you are missing this resolver like this in your dispatcher serlet:
<bean name="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
</bean>
Take look at this:
http://spring-json.sourceforge.net/quick_simpleform.html
You have to create file views.xml in yoru WEB-INF direcotry with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
</beans>

Categories

Resources