Web Service in Spring and Portlet environment - java

I am beginner in Web Service and using
Spring 3.0 and spring-webmvc-portlet 3.0
javax.portlet 2.0
I have controller as follows
#Controller(value = "myController")
#RequestMapping(value = "**VIEW**")
public class MyController {
// Controller logic
}
Now, I want to create Web Service using RESTful API in portlet environment.
Please guide me How can i write the Web Service which will return JSON or XML data.
I am still struggling with Web Service not getting WS called.
I am pasting my conf files
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/itemCatalog-portlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>webServiceTest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webServiceTest</servlet-name>
<url-pattern>/myWebService/*</url-pattern>
</servlet-mapping>
item-portlet.xml
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.main.mypackage" />
<bean
class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="myPropertyEditorRegistrar" />
</list>
</property>
</bean>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>content.Language-ext</value>
</list>
</property>
</bean>
<bean id="viewResolver"
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>
<bean name="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="false" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
webServiceTest-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
portlet.xml
itemCatalog
org.springframework.web.portlet.DispatcherPortlet
text/html
view
content.Language-ext
Controller
#Controller
public class WebServiceTest {
#RequestMapping(value = "/myWebService/testing", method = RequestMethod.GET)
public String testMethod() {
return "HELLO WORLD ! SUCCESS";
}
}
I am trying to Hit with
localhost:8080:/myappname/myWebService/testing
Getting no result.

To create Web Service in portlet environment.
1. We need to use org. springframework.web.servlet.DispatcherServlet which is front controller for all the controllers available. All the HTTP request will be dispatched using Dispatcher servlet.
Add an entry in web.xml
<servlet>
<servlet-name>springwebservice</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springwebservice</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Please refer below link for dispatcher servlet read carefully
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
Now importantly each DispatcherServlet must have own WebApplicationContext. WebApplicationContext is nothing but an xml file comprises of controllers,view resolver,beans,etc .
Create file named springwebservice-servlet.xml in WEB-INF. springwebservice-servlet.xml is a WebApplicationContext.
Note
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.
Make sure new WebAppicationContext is created for DispatcherServlet and configure it according to need.
Please guide me if mistaken somewhere.

Related

Spring Controller Issue

Recently I've got a problem with simple Spring MVC Application, particularly with controller.
Here is my controller code snippet:
#Controller
public class MyController {
#RequestMapping(value="/", method=RequestMethod.GET)
public String m1(Model model){
return "form";
}
}
Here is my web.xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And here is bean configuration file:
<context:component-scan base-package="ua.macko.controller"/>
<mvc:annotation-driven/>
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
In the jsps folder I've got two jsp files: hello.jsp and form.jsp.
When I'm trying to achieve root page of application, such as http://localhost:8080/WebTest/ I'm ALWAYS getting hello.jsp REGARDLESS of what value I return in m1 method...whether it is "hello", "nothello", "iamnotapage" etc.
I am using Eclipse and Spring 3.2.8.
When you start Spring application in log you should see something like this :
INFO: Mapped URL path [/] onto handler 'welcomeController'
If you do not see your controller on this list it means you should check:
context:component-scan base-package="ua.macko.controller"
because your controller is not visible to Spring
If you see two mappings than yours is overridden.
If you do not see any mapping like this than most probably Beau Grantham is right, or some other config problem is there.
Is the path correct? I see you have jsps, try /WEB-INF/jsp/?
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

What happens when we don't register ContextLoaderListener?

I tried to find some explanation for what really happens when we do not register ContextLoaderListener in our web.xml file, mainly because I have a simple Spring + Hibernate app that works fine if I DO NOT declare ContextLoaderListener. When I do, I get 404 error.
web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
applicationContext.xml:
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="org.myfantasticwebsite"/>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/pizzashop"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>org.myfantasticwebsite</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
I also have index.jsp that just displays some stuff from database. All 3 files (web.xml, applicationContext.xml and index.jsp) are located in WEB-INF directory, and everything works fine until I add ContextLoaderListener bean to web.xml. After, I get Page not found error on address localhost:8080/pizzashop.
This is just a simple tutorial I found on internet, that's why all configuration is in one file. I was actually trying make separate config files - 2 files stemming from web.xml (dispatcher-servlet.xml with web related config and applicationContext.xml with everything else). Further more to extract hibernate specific config to hibernate.cfg.xml, and spring+hibernate config to hibernate-context.xml.
Can someone please explain why I get 404 error, I'm stuck here for a week now. Thank you.
This is the only controller - PizzaController:
#Controller
#RequestMapping("/")
public class PizzaController {
#Autowired private PizzaDAO pizzaDAO;
/**
* This handler method is invoked when
* http://localhost:8080/pizzashop is requested.
* The method returns view name "index"
* which will be resolved into /WEB-INF/index.jsp.
* See src/main/webapp/WEB-INF/applicationContext.xml
*/
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Pizza> pizzas = pizzaDAO.findAll();
model.addAttribute("pizzas", pizzas);
return "index";
}
}
UPDATE: web.xml with ContextLoaderListener:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Autowire gives null in customlogouthandler and custom userdetails

My autowire works fine from Controller and all the subclasses down below the controller. But when I try to Autowire any bean (using annotations) from Spring Security module like through UserDetails or through my customlogout handler.
I have read and found two ways to solve it
1. Remove
2. Move some code to the parent context.xml. But looks like this doesnt help me.
My web.xml
...
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/database-context.xml,
/WEB-INF/spring/application-security.xml
</param-value>
</context-param>
My servlet-context file has the following:....
<mvc:resources mapping="/resources/**" location="/" />
<!-- 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>
<context:component-scan base-package="com.inventory" />
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="classpath:messages"></beans:property>
<beans:property name="defaultEncoding" value="UTF-8"></beans:property>
</beans:bean>
Please help..
It indicates your autowired annotations are not activated.
Include
<context:annotation-config>
in your database-context.xml, application-security.xml files.

Spring MVC No handler found

I'm newbie to spring mvc and trying to develop a very basic login webapp. I get the below error while running the project. I have tried almost everything and could not fix this error since last two weeks. Please can someone help me.
May 21, 2013 2:37:12 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringWeb/WEB-INF/jsp/loginnn.jsp] in DispatcherServlet with name 'spring'
My jsp pages resides under WEB-INF/jsp. The method loginpage in my controller is gettting invoked but the view name is not being rendered and resolved. Greatly appreciate your help.
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>testspring</display-name>
<servlet>
<servlet-name>frontcontrol</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>frontcontrol</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
frontcontrol-servlet.xml
<context:component-scan base-package ="com.shell.spring.testspringapp">
</context:component-scan>
<bean id ="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller class
#Controller
public class Firstcontrol {
#RequestMapping(value="/")
public ModelAndView invokeme(Model m)
{
ModelAndView mav=new ModelAndView();
mav.setViewName("result");
System.out.println("In method");
return mav;
}
#RequestMapping(value="/submit" ,method=RequestMethod.GET)
public String submit(Model m)
{
System.out.println("In submitmethod");
return "submit";
}
}
Since you're mapping your DispatcherServlet to '/' try adding <mvc:default-servlet-handler/> to your spring-servlet.xml
I saw same error, turned out that you need enable MVC annotations separately
<mvc:annotation-driven/>
In addition to
<context:Annotation-config/>
<context:component-scan base-package="your base packege " />
You should check the following section in spring configuration xml. Maybe you copied it from somewhere and forgot to make it your package name. Spring will not be able to scan packages if it so and eventually show this error.
In the web.xml file the configuration file (spring-servler.xml) should be specified to be used by the dispatcher servlet, since your not using the conventional name, which is the [servlet-name]-context.xml.
Since Spring cannot find the configuration file for the dispatcher servlet the viewresolver is never registered. I assume that 'spring-servler.xml is located within the WEB-INF folder in my example, so you may need to adjust.
Also notice I switched the servlet mapping to / which helps if you need to resolve static resources, since / acts as a catch all as opposed to mapping everything through the dispatcher.
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring-servler.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
You could also try using a regular view resolver, if your not using JSTL.
Replace the jstl view resolver:
<bean id ="viewResolver"
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>
With:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Try returning a String from your controller that specifies the view name:
#RequestMapping(value="/")
public String loginpage(Model model)
{
Employee emp=new Employee();
ModelAndView mav=new ModelAndView();
model.addObject("emp", emp);
return "loginnn";
}
#sanjay and #Will Keeling are both right. It is required to use <mvc:default-servlet-handler/> (as the last handler) and enable both <mvc:annotation-driven/> and <context:Annotation-config/>

Issues with setting URL mappings in Spring MVC 2.5

I have the following in my web.xml file:
<servlet>
<servlet-name>onBoardingUI</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
and in my sample-servlet.xml file:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<!-- <property name="maxUploadSize" value="100000" /> -->
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/fileupload.form=fileUploadController
</value>
</property>
</bean>
<bean id="fileUploadController" class="com.wrightexpress.si.onboardingui.web.FileUploadController">
<property name="commandClass" value="com.wrightexpress.si.onboardingui.service.UploadFile" />
<property name="formView" value="process-file" />
<property name="successView" value="results" />
</bean>
<bean id="viewResolver"
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>
Now when I deploy the application, I get a 404 when hitting the context root. No exceptions or anything in the server log. I realized that I am setting the URL handler, but for some reason no requests are getting through. I've tried various forms of declaring the servlet-mappings in web.xml to no avail. I have a simple file upload form that has an action of fileupload.form.
Thanks!
EDIT: I have a series of jsp pages that are currently being served up via the viewResolver defined above. These stop working when I add the urlMapping bean in there. Now, I don't know how I should handle this, if I just apply a servlet-mapping of /* in the web.xml file, how do I specify in the sample-servlet.xml file which controller to tie each jsp to other than individually? Or how do I keep my web.xml like it is and only have the defined URL handler handle the fileupload.form action?
are you sure your web.xml ist right?
you have a DispatcherServlet called "onBoardingUI" but your servlet-mapping tags do look for a servlet called "sample".
shouldnt the servlet-mapping be:
<servlet>
<servlet-name>onBoardingUI</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>onBoardingUI</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>onBoardingUI</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
Once you start defining URL Mappings, you will need to tell spring mvc how to handle any URLs not specifically mapped. Try adding the following mapping:
/*=urlFilenameViewController
and the following bean to handle these requests:
<bean id="urlFilenameViewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
The UrlFilenameViewController will pass the URI directly to the view resolver. e.g. example.com/index.html will get mapped to WEB-INF/jsp/index.jsp
If you need to use the full path of the URI, (e.g. example.com/help/index.html maps to WEB-INF/jsp/help/index.jsp)
then set the alwaysUseFullPath property on the URL Mapping
<property name="alwaysUseFullPath" value="true" />

Categories