Spring MVC mapping query parameters instead of URI templates values with #PathVariable - spring-mvc

#RequestMapping(value = "/account/{id}", method = RequestMethod.GET)
public ModelAndView getAccount(#PathVariable String id)
throws ProfileNotFoundException {
System.out.println(id);
return null;
}
.../account/12345 results in null
.../account/test?id=12345 '12345' results in 12345
Not sure how to fix this but I'd like the first link to work instead of the second. Here is my webmvc-config.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.twheys.lexika.web.**"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<mvc:annotation-driven/>
<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/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

Just specify it as #PathVariable("id") - without that the HandlerMethodArgumentResolver responsible for resolving the value of the argument tries to figure out the parameter value by parameter name, the parameter name (id) gets lost during compilation though(unless debug symbols are on during compilation, which typically it is not).

#RequestMapping(value = "/authors/{authorId}")
public ModelAndView getAuthorById(#PathVariable String authorId) {
Author author = bookService.getAuthorById(authorId);
ModelAndView mav =
new ModelAndView("bookXmlView", BindingResult.MODEL_KEY_PREFIX + "author", author);
return mav;
}
Above Code works fine for me. Kindly use in similar manner.

Related

Spring framework No adapter for handler

I am upgrading Spring framework from very old version to 5.3 - I made updated to controller and configuration file. I am getting "javax.servlet.ServletException: No adapter for handler for Controller" error.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<context:component-scan base-package="abc.controller,abc.bean,abc.bean.command,abc.validator" />
<context:annotation-config />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<!-- Controllers -->
<bean id="uploadFormController" class="abc.controller.UploadFormController">
<property name="mailSender"><ref bean="mailSender"/></property>
<property name="message"><ref bean="uploadConfirmationEmail"/></property>
<property name="submissionDao"><ref bean="submissionDao"/></property>
<property name="providerDao"><ref bean="providerDao"/></property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
</property>
<property name="interceptors">
<list>
<ref bean="securityInterceptor"/>
</list>
</property>
<property name="mappings">
<props>
<prop key="upload.html">starSiSpreadsheetUploadFormController</prop>
</props>
</property>
</bean>
<bean id="securityInterceptor"
class="abc.interceptor.SecurityInterceptor">
<property name="defaultUser"><value>${abc.defaultUser}</value></property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix"><value>/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>`
package abc.controller;
#Controller
#RequestMapping("/upload.html")
public class UploadFormController {
#Autowired
private SpreadsheetUpload bean; //CommandClass
#Autowired
private MailSender mailSender;
#Autowired
private SimpleMailMessage message;
#Autowired
private SubmissionDAO submissionDao;
#Autowired
private ProviderDAO providerDao;
protected String onSubmit(HttpServletRequest request,
HttpServletResponse response, BindException errors)
throws Exception
{
// let's see if there's a provider
if (bean.getProvider() == null)
{
log.info("No provider selected.");
throw new DataEntryException("No provider selected. ");
}
return "redirect:upload.html";
}
protected Map referenceData(HttpServletRequest request) throws Exception
{
// TODO - switch code over to using LDAP queries
HttpSession session = request.getSession();
//Logic goes here..
Map map = new HashMap();
map.put("admin", admin);
return map;
}
}
Could someone take a look and help me on this? I have been trying since last two days and no luck so far. Thank you!
There is nothing wrong in my code. I have another method called "OnSubmit" which is causing the problem.

How to update Spring 4.1.6.RELEASE version to my project?

java.lang.IllegalStateException: Could not find #PathVariable [pathVars] in #RequestMapping
How can I update Spring 4.1.6 RELEASE version to my project?
#Controller
public class HelloController {
#RequestMapping("/welcome/{countryName}/{userName}")
public ModelAndView helloWorld(#PathVariable Map < String, String > pathVars) {
String name = pathVars.get("userName");
String country = pathVars.get("countryName");
ModelAndView modelAndView = new ModelAndView("HelloPage");
modelAndView.addObject("msg", "Hello " + name + "You are from" + country);
return modelAndView;
}
This is my spring-dispatcher-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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.learningspringmvc.controller"></context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
The PathVariableMapMethodArgumentResolver which you're trying to use is present in Spring 4.1.6 RELEASE, so your code should work.
You have probably not enabled Spring Web MVC.
You either need to include <mvc:annotation-driven/> in your xml config, or use the #EnableWebMvc.

spring servlet-mapping / url-pattern

I have this servlet-mapping
<servlet-mapping>
<servlet-name>devicesWeb</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>/device-catalogue</url-pattern>
<url-pattern>/device-catalogue/</url-pattern>
<url-pattern>/device-catalogue/*</url-pattern>
<url-pattern>/search/search.do</url-pattern>
</servlet-mapping>
With these 2 methods:
#RequestMapping(value = "/device-catalogue", method = RequestMethod.GET)
private String initForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result, HttpServletRequest request, Model model, Locale locale) {
sessionHelper.checkSessionAttributes(request, locale);
return SEARCH_VIEW;
}
#RequestMapping(value = { "/search/showProductDetails.do", "/device-catalogue/{id}" }, method = { RequestMethod.GET, RequestMethod.POST })
private String showProductDetails(#ModelAttribute("searchForm") final SearchForm searchForm,
HttpServletRequest request, Model model, Locale locale) {
StringTokenizer st = new StringTokenizer(StringEscapeUtils.escapeHtml(searchForm.getItemId()),"=");
if (st.countTokens()>1) {
String awardId=st.nextToken();
String id=st.nextToken();
Item item = deviceService.getItemByAwardId (Long.parseLong(id), awardId);
normalizeWebsiteURL (item);
orderCountriesAvailability(item.getCountriesAvailability(), locale);
model.addAttribute("item", encodeItemForHTML(item));
}
return PRODUCT_DETAIL_VIEW;
}
This URL works fine:
http://127.0.0.1:7001/eDevices/device-catalogue
But not this one (I got a 404) !
http://127.0.0.1:7001/eDevices/device-catalogue/16720
If I add this to the web.xml it works
<url-pattern>/product-catalogue/16720</url-pattern>
Don't write a <url-pattern> per url. Use the front controller of the spring mvc (DispatcherServlet) to be responsible for handling all application requests.
In order to do that, in your web.xml you need something like:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and a dispatcher-servlet.xml beside that:
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.test" /> <!-- specify your base package instead of "com.test" -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
<mvc:resources mapping="/resources/**" location="WEB-INF/resources/" /> <!-- Not necessary but it's nice to address resources(css, images, etc) like this -->
</beans>

I can not access(error 404) to my spring mvc web app after adding spring websockets

After adding Spring web sockets (that works fine) to my existing spring mvc app I can not access to the app (Error 404 for all the app urls) but I can access to the socket fine. If I revert the changes that I added to spring-mvc.xml file and then deploy them, the app works fine. I'm not sure what I doing wrong, could you please help me?
I just was following this tutorial http://syntx.io/using-websockets-in-java-using-spring-4/ I'm using spring 4.
This is my Spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:websocket="http://www.springframework.org/schema/websocket"
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/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">
<context:component-scan base-package="com.mobile.automation.view.controller"/>
<context:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="websocket" class="com.mobile.automation.sockets.WebsocketEndPoint"/>
<websocket:handlers>
<websocket:mapping path="/testing" handler="websocket"/>
<websocket:handshake-interceptors>
<bean class="com.mobile.automation.sockets.HandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
</beans>
WebsocketEndPoint.java
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
#Controller
public class WebsocketEndPoint extends TextWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
super.handleTextMessage(session, message);
TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
session.sendMessage(returnMessage);
}
I don't see anything related to other Controllers or any MVC configuration in this example.
Maybe you're missing something like this in your spring-mvc.xml file?
<?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>

spring mvc json Internal Server Error

I have problem with returning JSON from controller with response body, i see that that hibernate make query to database but in moment of converting list to json i get in firebug Internal Server Error 500;
my servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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">
<annotation-driven />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:annotation-config />
<context:component-scan base-package="pl.daniluk.spotted.controller" />
<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass">
<beans:value>
org.springframework.web.servlet.view.tiles2.TilesView
</beans:value>
</beans:property>
<beans:property name="contentType" value="text/html; charset=UTF-8"></beans:property>
</beans:bean>
<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/tiles.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
and controler with #ResponseBody
#Controller
#RequestMapping("/place")
public class PlaceControler {
#Autowired
private PlaceService placeService;
#RequestMapping(value = "/list", method = RequestMethod.GET)
#ResponseBody
public List<Place> getAllPlaces() {
return placeService.getAllPlaces();
}
}
any clues where i'm making mistake?

Resources