I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service.
This is my Controller class
#RequestMapping("/*")
public class Opinion {
private FeedbackService fs;
public Opinion(FeedbackService fs){
this.fs=fs;
}
#RequestMapping(value="/givefeedback",method=RequestMethod.POST)
public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException
{
ObjectInputStream in=new ObjectInputStream(request.getInputStream());
serialize.Feedback feedback=(serialize.Feedback)in.readObject();
fs.writeFeedback(feedback);
response.setStatus(200);
}
My mvc-config.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:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="poll_Web" class="sef.controller.Opinion">
<constructor-arg ref="feedbackService" />
</bean>
<context:component-scan base-package="sef.controller" />
</beans>
My web.xml
<servlet>
<servlet-name>opinionDispacher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>opinionDispacher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml
</param-value>
</context-param>
I am using the URL localhost:8080/feedback/givefeedback. The app is deployed as feedback.war. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
You're missing
<mvc:annotation-driven/>
from your servlet context configuration. This element will discover #Controller beans and their #RequestMapping methods and register them as handlers.
You'll need to add the appropriate XML namespace and schema location for that namespace.
Make Opinion a #Controller and remove
#RequestMapping("/*")
it doesn't really serve any purpose.
You have also defined the Opinion bean twice in mvc-config.xml. Remove bean definition for bean id poll_Web.
Related
I am trying to create a Spring RESTful API very a basic application from scratch, but I am not able to access the controller. I could access JSP file but not controller. I have tried with to annotate with #RestController as well but it didn't work. I am running on Tomcat 8.
Error is:
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists. WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<context:component-scan
base-package="com.controller />
<mvc:default-servlet-handler />
</beans>
My Controller is
#Controller
public class TransactionControllerImpl{
#Autowired
private TransactionService transactionService;
#RequestMapping(method = RequestMethod.GET, value="/transaction")
#ResponseBody
public String getTransactionList() {
try {
System.out.println("from controller");
return "HEllow rahul";//transactionService.getTransactionList();
}
catch (Exception e) {
return null;
}
}
If you are creating application context separately, you should provide context param and value as location of your context.xml file.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
For your error the controller is not accessible,it might be due to :-
<context:component-scan
base-package="com.controller />
check if you have written correct base-package name or try using
<context:component-scan base-package="..package name..">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
Hope it helps.
Remove listener from web.xml because you have only one context xml. If you want to load multiple context xml add listener and context param.
I'm new to Spring Framework and am currently trying to figure out how to load a file called servlet-context.xml automatically at application start. This file contains a bean definition which I'd like to use using #Autowired in my application code.
Note: I know that I can do something like the following to manually load beans, but this doesn't work when you're using #Autowired:
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
SomeObjectType x = (SomeObjectType)context.getBean("someObjectType");
I found this code sample from another tutorial which sort of tells how to load servlet-context.xml, but it was taken from a web application project which used MVC pattern. I don't have an web-app using MVC, so I don't think it applies to me:
<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>
The contents of my servlet-context.xml file are the following:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/Database"/>
</beans:bean>
</beans:beans>
So what's the cleanest and simplest way to load servlet-context.xml file?
you can uselistener to load context...
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</context-param>
It seems that dispatcher-servlet unable to perform component scan using.
<context:component-scan base-package="abc" />
In my controller file (HelloController.java) under package abc. Code is written as follows:
#Controller
#RequestMapping("/hello")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello"; //I have already made hello.jsp in web-inf/jsp/
}
}
My Application name is SpringMiddle. When try url as:
http://localhost:8080/SpringMiddle/hello.htm
I do have following url pattern in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
It shows me error HTTP 404 not found.
EDIT: : it shows me warning
WARNING: No mapping found for HTTP request with URI [/SpringMiddle/hello.htm] in DispatcherServlet with name 'dispatcher'
You have to enable MVC in Spring. In xml config you can do it in such way:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
</beans>
and in JavaConfig:
#Configuration
#EnableWebMvc
public class WebConfig {
}
Please refer to Spring documentation
if you are referring to an mkyong tutorial, I didn't use the annotations: #Configuration
#EnableWebMvc, problem is you are using both annotations and xml declaration.
Annotation for setting the url:
#Controller
#RequestMapping("/hello")
you should remove this part:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
and you'll be able to visit the url:
http://localhost:8080/SpringMiddle/hello
Also make sure you have this in your web.xml:
<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>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
the dispatcher-servlet.xml is where the component scanning is declared
My Web application is polling a Database for changes and Showing those changes on a JSP. The Database is changed by a legacy System and no possibility to get an event on Data change.
My approach is to poll the Database and synchronizing the data with an Application bean. If the data has changed, I use a push mechanism to update the JSP page. The Thread that polls the database is spawned by the Application bean.
I’m already using spring in my Web application so I want to use the spring #Scheduled annotation because I don’t want to spawn a Thread and let Spring handle the periodical execution. But the the Method is not execute Periodically.
I'm using Tomcat and MS Sql Server.
My Application bean looks like this
#Named("agentData")
#Scope("application")
public class AgentDataBean implements Serializable {
...
#Scheduled(fixedRate=5000)
public void loadData() {
// do database poll
}
...
}
My Spring and Web Xml look like this
<?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>JavaServerFaces</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>#{login.theme}</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
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/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/config/database.properties" />
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource" p:driverClassName="${jdbc.driverClassName}"
p:password="${jdbc.password}" p:url="${jdbc.url}" p:username="${jdbc.username}" />
<!-- Activates annotaion-based bean configuration -->
<context:annotation-config />
<!-- needed is for #Configurable -->
<context:component-scan base-package="de.cpls.alo.dashboard" />
<tx:annotation-driven />
<!-- Activates #Scheduled and #Async annotations fpr scheduling -->
<task:annotation-driven executor="executorWithPoolSizeRange" scheduler="taskScheduler"/>
<task:executor id="executorWithPoolSizeRange"
pool-size="5-25"
queue-capacity="100"/>
<!-- Defines a ThreadPoolTaskScheduler instance with configurable pool size.
The id becomes the default thread name prefix. -->
<task:scheduler id="taskScheduler" pool-size="1"/>
This question is a solution approach to this Question
Is there a best practice for showing database changes on a JSP
My Solution, using a SchedulerComponent
#Named("scheduler")
#Component
public class SchedulerComponent {
private List<IScheduledComponent> components;
public SchedulerComponent() {
this.components = new ArrayList<IScheduledComponent>();
}
public void register(IScheduledComponent component){
this.components.add(component);
}
#Scheduled(fixedRate = 5000)
public void doAllWork() {
try {
for(IScheduledComponent component : this.components){
component.doWork();
}
System.out.println("SchedulerComponent.doAllWork()");
} catch (Exception e) {
e.printStackTrace();
}
}
}
An Interface for Scheduled Execution
public interface IScheduledComponent {
public void doWork();
}
An let the Data Bean Implement the Interface and Register to the SchedulerComponent
#Named("agentData")
#Scope("application")
public class AgentDataBean implements Serializable,IScheduledComponent {
...
public void doWork() {
// do database poll
}
...
}
Now i got Scheduled with Spring and i got FacesContext in AgentDataBean so i can Execute a Icefaces Push.
I'm trying to improve my spring mvc configuration so as to not require a new config file for every servlet I add, but I'm running into problems. I've tried using this tutorial as a starting point, but I'm running into an issue that I can't figure out.
The problem is that when I do a GET to my servlet, I get back a 404 error. Here's my config and a representative java snippet from a Controller:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>SightLogix Coordination System</display-name>
<description>SightLogix Coordination System</description>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
/WEB-INF/application-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/slcs/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
/WEB-INF/application-security.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>
application-context.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"
default-init-method="init" default-destroy-method="destroy">
<mvc:annotation-driven />
<context:component-scan base-package="top.level" />
</beans>
application-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.xsd">
<http>
<intercept-url pattern="/**" access="ROLE_MANAGER" requires-channel="https" />
<http-basic />
</http>
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder hash="sha"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="myUserDetailsService"
class="path.to.my.UserDetailsServiceImpl">
</beans:bean>
</beans:beans>
Snippet of a Controller class (one of many, but they all look essentially like this):
#Controller
#RequestMapping("/foo.xml")
public class FooController
{
#RequestMapping(method=RequestMethod.GET)
public void handleGET(HttpServletRequest request, HttpServletResponse response) throws IOException
{
...
Can anyone tell me what I'm doing incorrectly?
Thanks!
The only thing out of place here is that you've used the same context config files for both the root webapp context and your servlet context. This is almost guaranteed to be a bad idea, and will result in a lot of weird behaviour. This may well be the cause of your problem.
The ContextLoaderListener is configured with the contextConfigLocation <context-param>, and creates and manages the root WebApplicationContext.
The ServletDispatcherServlet is configured with the contextConfigLocation <init-param>, and creates and manages the servlet WebApplicationContext.
The root WebApplicationContext is the parent of the servlet appcontext, i.e any beans in the root WebApplicationContext are visible to those beans in the servlet WebApplicationContext.
Your first step should be to separate those configurations. With the correct beans in the correct places (e.g. all MVC stuff has to go in the servlet context). Do not share bean definitions between the two, it'll just get confusing and/or broken.
This doesn't answer your question directly, but I've always found it helpful to enable debug logging in Spring when I can't figure out what is going wrong.
Below are two that I commonly use in my logging.properties file:
org.springframework.beans.factory.support.level=FINEST
org.springframework.security.level=FINEST
Do you have more than one GET RequestMapping in your controller by any chance? If there are more than one and there is ambiguity in resolving them to a particular request Spring does not map to any of the ambiguous GET mappings.