two servlets which point on the same package and webservice - java

Can anyone tell me please if what i am doing is right ?
I have this web.xml file with my servlets declared inside, i wanted to creat another servlet that access [reach] the same webservice
it doesn't work and i don't know what i am missing can you help please ?
Here is my servlets and code:
<!-- old servlet-->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/api-r-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/sitesApi/*</url-pattern>
</servlet-mapping>
<!-- my secod servmet V2 -->
<servlet>
<servlet-name>webservice</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/api-web-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webservice</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
So for my other XML file, api-web-servlet it's quite the same :
<?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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
>
<context:annotation-config/>
<context:component-scan base-package="com.me.project.rest.api" />
<mvc:annotation-driven />
</beans>
for my URL test i use:
http://localhost:8080/sitesApi/v1/mysite?id=1&fields=site.name
and it works but when i try with the other servlet it doesnt :
http://localhost:8080/api/v1/mysite?id=1&fields=site.name
******* Edition*****
#RequestMapping(value = "/v1/mySite", method = RequestMethod.GET)
public #ResponseBody
Object SitesV1( #RequestParam(value = "ajouterstatus", required = false) Integer ajouterstatus,
#RequestParam(value = "monadresse", required = false) String monadresseHttpServletRequest request, HttpServletResponse responseHttp{
try {
appname = request.getHeaders( "Name" ).nextElement().toString();
} catch ( Exception e ) {
return new Result( "", ": AppName is Empty" );
}
So exactly the same thing with the other method
#RequestMapping(value = "/v2/mySite", method = RequestMethod.GET)
public #ResponseBody
Object SitesV2( #RequestParam(value = "ajouterstatus", required = false) Integer ajouterstatus,
#RequestParam(value = "monadresse", required = false) String monadresseHttpServletRequest request, HttpServletResponse responseHttp{
try {
appname = request.getHeaders( "Name" ).nextElement().toString();
} catch ( Exception e ) {
return new Result( "", ": AppName is Empty" );
}
Any idea ??
Thank you

You can use as many Dispatcher Servlets as you want but each one of them will need to be configured with their own xml file.
So, for your servlet named 'api', you must be having the configuration file in place named as: 'api-servlet.xml'.
Now, you need to have 'webservice-servlet.xml' in place for your 'webservice' dispatcher servlet to work.
You can refer to following answers:
How does DispatcherServlet work if we have multiple XML Configuration file?
Multiple application context, multiple dispatcher servlets?

Related

WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'

My project is a maven project when i run the project on tomcat it shows
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'
I tried all possibilities to resolve but all in vein, can somebody help me out to resolve this issue
my controller :
package com.spring.login.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.spring.login.beans.Customer;
import com.spring.login.services.CustomerService;
import com.spring.login.validation.CustomerValidation;
#Controller
public class CustomerController {
#Autowired
private CustomerService customerService;
#RequestMapping(value="/" , method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
#RequestMapping(value="/register", method = RequestMethod.GET)
public String showForm(ModelMap model){
model.put("customerData", new Customer());
return "/register";
}
#RequestMapping(value= "/register", method= RequestMethod.POST)
public String saveForm(ModelMap model, #ModelAttribute("customerData") #Valid Customer customer, BindingResult br, HttpSession session){
CustomerValidation customerValidation = new CustomerValidation();
customerValidation.validate(customerValidation, br);
if(br.hasErrors()){
return "/register";
}
else{
customerService.saveCustomer(customer);
session.setAttribute("customer", customer);
return "redirect:success";
}
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logOut(ModelMap model, HttpSession session){
session.removeAttribute("customer");
return "redirect:login";
}
#RequestMapping(value="/success", method = RequestMethod.GET)
public String logOut(ModelMap model){
model.put("customer", new Customer());
return "redirect:success";
}
}
my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd" >
<display-name>SpringLoginApplication</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringLoginApplication</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/SpringLoginApplication-servlet.xml
</param-value>
</init-param>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringLoginApplication</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
my SpringLoginApplication-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.spring.login.controller" />
<context:component-scan base-package="com.spring.login.dao" />
<context:component-scan base-package="com.spring.login.beans" />
<context:component-scan base-package="com.spring.login.services" />
<context:component-scan base-package="com.spring.login.validation" />
<mvc:annotation-driven />
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="com.spring.login.beans.Customer" init-method="getC_id" destroy-
method="getC_name">
<property name="c_id" value="1234"/>
<property name="c_name" value="Sanjay"/>
</bean>
</beans>
A working response would be highly appreciated!
ANY OTHER INFO REQUIRED, PLS LET ME KNOW
I had the same problem few days before, and I got bellow solution.
#Controller
#RequestMapping(value="/" )
public class CustomerController {
//do your stuff here
#RequestMapping(method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
//Rest of your stuff goes here
}
Since you have configured your Dispatcher servlet to handle your context in stead of all possibility which people generally do by adding this (/*), so above provided code snippet will work and redirect your context to /login which you want(if i'm not wrong). Cheers!!!!

Spring #Autowired gives new instance instead of initialized session scoped bean

I am developing application using Spring and I need to initialize Ticket object in session and then get it from another controller.
I have two controllers, so there are two xml contexts.
web.xml
<web-app id="WebApp_ID" 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">
<display-name>Spring Web MVC Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/index-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
rest-context.xml
<beans ...>
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="menu.MenuController"/>
</beans>
index-context.xml
<beans ...>
<mvc:annotation-driven/>
<mvc:resources mapping="/**" location="/"/>
<context:annotation-config/>
<bean class="auth.IndexWebController" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
In the spring-context I have my Ticket bean:
<bean id="tickerProvider" class="TicketProviderImpl" scope="session">
<aop:scoped-proxy/>
together with the other beans.
This are what my controllers look like:
IndexWebController.java
#Controller
#SessionAttributes("user")
public class IndexWebController {
private static Logger logger = LoggerFactory.getLogger(IndexWebController.class);
#Autowired
private TicketProviderImpl ticketProvider;
#ModelAttribute("user")
public User populateUser() {
return new User();
}
#RequestMapping(value = "/", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView printIndex(#ModelAttribute("user") User user,
#RequestParam(value = "iv-user", required = false) String login,
#RequestParam(value = "iv-groups", required = false) String groups) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index.html");
<...>
ticketProvider.setLogin(login);
logger.info("Пользователь установлен в " + login);
<...>
MenuController.java
#Controller
public class MenuController {
#Autowired
private TicketProviderImpl ticketProvider;
#ResponseBody
#RequestMapping("/getMenuList")
public MenuListDTO getMenuList(
#RequestParam(value = "menuId", required = true, defaultValue = "-1") long menuId,
#RequestParam(value = "parentId", required = true, defaultValue = "0") long parentId) {
<...>
System.out.println(ticketProvider.getLogin());
<...>
}
}
The problem is that when I autowire ticketProvider bean in the MenuController I get a new instance of it, not those that has been initialized in the IndexWebController. Actually I get null, but waiting for the login.
Where is the mistake or some misunderstanding of using session scoped beans?
According to this you will need another listener to expose your session to the application.
Hence adding <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> should do the trick.

Receiving payload request and displaying it on a webpage using spring

First of all I'm new to Spring and tried my best to get this working. So this is my question.
I have a spring MVC project which is supposed to receive a request payload (JSON request) and display the payload body on a webpage. Please see my project content and the controller class below
#Controller
public class CallbackPayloadController {
public CallbackPayloadController() {
System.out.println("In controller class!!!!");
}
#RequestMapping(value = "/requestreceiver", consumes = "application/json", method = RequestMethod.POST)
public void receivePayload(#RequestBody String payload) {
System.out.println("In the controller method....");
System.out.println("Payload is : " + payload);
}
}
Now if I do a POST to http://localhost:8080/PayloadReceiver/requestreceiver/ using POSTMAN it says HTTP STATUS 404. My Json content that I am posting is
{
"key":"123"
}
My web.xml is as follows
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>PayloadReceiver</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>requestreceiver</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>requestreceiver</servlet-name>
<url-pattern>/requestreceiver.jsp</url-pattern>
<url-pattern>/requestreceiver.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Second question is if I successfully receive the payload, how do I display the payload content on a new webpage?
Try to add the return statement to your method like this:
#RequestMapping(value = "/requestreceiver",consumes="...",method = RequestMethod.POST)
public String receivePayload(...)
...
return "requestreceiver";

Spring : No mapping found for HTTP request

I strangely have this problem :
[04/07/14 11:31:09:009 CEST] WARN servlet.PageNotFound: No mapping found for HTTP request with URI [/datapine-backend/heroku/resources] in DispatcherServlet with name 'rest'
However, I checked the logs and my method is already mapped!
annotation.RequestMappingHandlerMapping: Mapped "{[/heroku/resources/],methods=[POST],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.http.ResponseEntity<java.lang.String> com.datapine.heroku.HerokuController.provision(net.sf.json.JSONObject)
This my method :
#Controller
public class HerokuController {
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<String>(response.toString(),HttpStatus.OK);
}
This is my web.xml
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/heroku/*</url-pattern>
</servlet-mapping>
and this is the rest-servlet.xml :
<beans:import resource="classpath:spring-properties-loader.xml"/>
<context:component-scan base-package="com.datapine.heroku" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
</beans:beans>
what can be the problem?
thanks.

#RequestMapping in spring not working

I am new in Spring MVC. I created one controller newController.java in springproject. My code is below:
#RequestMapping(value = "/Receiver", method = RequestMethod.GET)
public void recvHttpGet(Model model) {
System.out.println("here get");
newmethod();
}
#RequestMapping(value = "/Receiver", method = RequestMethod.POST)
public void recvHttpPost(Model model) {
System.out.println("here post");
newmethod();
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String show(Model model) {
return "index";
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>ClassPath:/spring/applicationContext.xml, ClassPath:/spring/hibernateContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></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>
whenever I try to run it then index.jsp page is shown but whenever I try to call /Receiver url it shows a 404 error. Please help me. Also when I changed in recvHttpGet method return "index" it also shows a 404 error. Also nothing is wrote to the console.
I wants to just check which method calls so wants to write in console window but it does not show anything.
You need to return a JSP page, just like return "index";
If you have a receiver.jsp page in views, then...
#RequestMapping(value = "/Receiver", method = RequestMethod.GET)
public String recvHttpGet(Model model) {
return "receiver";
}

Categories