not able to fetch value from controller to view in spring from pojos - spring

I have the following code as
controller
#Controller
public class ProductController {
#RequestMapping("/products")
public String list(Model model) {
Product iphone = new Product("P1233", "iPhone 5s", new BigDecimal(500));
iphone.setDescription("pple iPhone 5s smartphone with 4.00-inch 640x1136 display and 8-megapixel rear camera");
iphone.setCategory("smart phone");
iphone.setManfactuer("Apple");
iphone.setUnitsInStock(1000);
model.addAttribute("product", iphone);
return "products";
}
product
private String productId;
private String name;
private BigDecimal unitPrice;
private String description;
private String manfactuer;
private String category;
private long unitsInStock;
private long uintsInOrder;
private boolean discountinued;
//getter and setter
now when I try to fetch value in jsp as:
<h3>${product.name}</h3>
<p>${product.description}</p>
<p>${product.unitPrice}USD</p>
<p>Available ${product.unitsInStock} units in stock</p>
web.xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
dispatcherServlet-servlet.xml
<mvc:annotation-driven />
<context:component-scan base-package="com.*" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
not getting any output in browser but when I change mapping to / instead of /products and loadOnStartUp to 1 for dispatcher servlet, everything is fine.
Is there any way to get values without mapping directly to dispatcherServlet as if I have more #controller classes then IDK, how to manage this?
EDIT
I have two controllers one is
#RequestMapping("/")
public String welcome(Model model) {
model.addAttribute("greeting", "Greetings of the day");
model.addAttribute("tagline", "this is the tagline");
return "welcome";
}
working fine and when i use this configuration not getting output in browser but when I change to
#RequestMapping("/")
public String list(Model model) {
Product iphone = new Product("P1233", "iPhone 5s", new BigDecimal(500));
iphone.setDescription("pple iPhone 5s smartphone with 4.00-inch 640x1136 display and 8-megapixel rear camera");
iphone.setCategory("smart phone");
iphone.setManfactuer("Apple");
iphone.setUnitsInStock(1000);
model.addAttribute("product", iphone);
return "products";
}
giving me output , but I want to use #RequestMapping("/products) , How to do that?

You have configured ViewResolver?
For example:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

配置 web.xml
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
你需要配置注解扫描包路径,及对应的视图解析器
<context:component-scan base-package="com.group.springmvc.controller" />
<mvc:annotation-driven enable-matrix-variables="true"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>

Related

No mapping found for HTTP request with URI in two DispatcherServlet

My web.xml states dispatcher-servlet url pattern as:
<!-- root context -->
<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>
</servlet>
<!-- admin context -->
<servlet>
<servlet-name>adminServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/admin-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>adminServlet</servlet-name>
<url-pattern>/admin/</url-pattern>
</servlet-mapping>
two servlet-mapping files are described as
<!--servlet-context.xml for appServlet-->
<annotation-driven />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/view/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!--admin-context.xml for adminServlet-->
<annotation-driven />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/view/admin/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
and I coded two controllers for the test. one is ok but the other met "error"
#Controller("admin.IndexController")
#RequestMapping("/admin")
public class AdminIndexController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
...
return "index";
//I thought this location will be /myContext/WEB-INF/view/admin/index.jsp
//and it run well
}
}
but the following controller couldn't find it's next page.
#Controller
#RequestMapping("/admin")
public class AddCategoryController {
#RequestMapping(value={"/category/add"}, method=RequestMethod.GET)
public String form(Model model){
...
return "addCategory";
//I thought the location will be /myContext/WEB-INF(/view/admin/category/)index.jsp
//but Spring forwarded to /myContext/WEB-INF/view/addCategory.jsp
}
}
if I write the code as "return admin/index;" this has no problem.
But I think AddCategoryController has to be handled by adminServlet and admin-context.xml.
Because AddCategoryController calls addCategory.jsp as the way of relative path, so they both should be on the same path. but I met fail... Can you tell me what is wrong?
You can achieve everything by registering servlet only once. Do not know why you are registering DispatcherServlet twice. You can give the root jsp folder path like "/WEB-INF/view/ and then in code you can move to different jsps in subfolders like /admin/index.jsp

not able to get value in view from controller in spring

I have this simple code to get data in view but I am not able to get nor I am getting any stack trace
#Controller
public class ControllerClass {
#Autowired
RepoisitiryClass repoisitiryClass;
#RequestMapping("testData")
public String getView(Model model) {
model.addAttribute("getData", repoisitiryClass.setData());
return "domain";
}
}
public class Domain {
private String domain;
public Domain(String domain) {
this.domain = domain;
}
public String getDomain() {
return domain;
}
}
#Repository
public class RepoisitiryClass {
private String dataDomain = "";
public RepoisitiryClass() {
System.out.println("inside Repo");
Domain domain = new Domain("this is domain");
dataDomain = domain.getDomain();
}
public String setData() {
return dataDomain;
}
}
<mvc:annotation-driven />
<context:component-scan base-package="com" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Now When ever I try to run url : http://localhost:8080/Test_path_Variable/testData it is getting me error 404 page not found.
Is there anyway to solve this error or I am doing somewere wrong?
and project Structure

springmvc and url-pattern

web.xml
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
controller
#Controller
#RequestMapping("/car/*")
public class CarController extends BaseController {
#RequestMapping("baojia.html")
public ModelAndView baojia() {
ModelAndView view = new ModelAndView();
view.setViewName("baojia");
return view;
}
when i visit http://mydomain/car/baojia.html and has this error:
[carloan]2016-04-21 09:01:31,177 WARN [org.springframework.web.servlet.PageNotFound] - <No mapping found for HTTP request with URI [/views/baojia.jsp] in DispatcherServlet with name 'springMVC'>
spring.xml ViewResolver
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="false"/>
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean>
and i have file in /views/boajia.jsp
whether i writer, it don't work
<mvc:resources mapping="/views/" location="/views/**" />
and i have another question, i wan't to matching this url-pattern: /api/*
and the controller is:
#Controller
#RequestMapping("/api/*")
public class CarApiController extends BaseController {
#RequestMapping("get")
#ResponseBody
public JsonResult getCars()
but it can't work
try #RequestMapping("/car") instead of #RequestMapping("/car/*")
And check below two links to understand, how request mapping defined.
can anybody explain me difference between class level controller and method level controller..?
http://duckranger.com/2012/04/advanced-requestmapping-tricks-controller-root-and-uri-templates/
URL mapping declaration is not proper use #RequestMapping("/car") and #RequestMapping("/baojia.html")

Spring MVC mapping not working: PageNotFound

When i visit localhost:8080/home - i get:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/home] in DispatcherServlet with name 'appServlet'
When i visit localhost:8080/ or localhost:8080/index all look ok.
Why one path works, and another don't?
And thing, that confuse me: localhost:8080/homepage.html - return me my home view.
So my project here: https://github.com/IRus/jMusic
my web.xml
<!-- Base servlet handles all requests to the application. -->
<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>
servlet-context.xml - i using tiles
<annotation-driven/>
<resources mapping="/resources/**" location="/resources/"/>
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/"/>
<beans:property name="suffix" value=".jsp"/>
<beans:property name="order" value="1" />
</beans:bean>
<beans:import resource="controllers.xml"/>
<beans:import resource="tiles.xml" />
<beans:import resource="i18n.xml"/>
<beans:import resource="themes.xml"/>
tiles.xml
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
<property name="order" value="0"/>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/views/tiles-definitions.xml</value>
</list>
</property>
</bean>
ErrorController
#Controller
public class ErrorController {
#RequestMapping("/403")
public String error403() {
return "403";
}
#RequestMapping("/404")
public String error404() {
return "404";
}
}
UserController
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("/")
public String index() {
return "redirect:/index";
}
#RequestMapping("/home")
public String home() {
return "home";
}
#RequestMapping("/login")
public String login() {
return "login";
}
#RequestMapping("/index")
public String listUsers(Map<String, Object> map) {
map.put("user", new User());
map.put("userList", userService.listUser());
return "user";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
return "redirect:/index";
}
#RequestMapping("/delete/{idUser}")
public String deleteUser(#PathVariable("idUser") Long idUser) {
userService.removeUser(idUser);
return "redirect:/index";
}
}
Logs
Here: https://gist.github.com/IRus/2ac97c66070001247011
Interested moment in logs:
Mapped URL path [/homepage.html] into handler 'userController'
I added, and delete thats #RequestMapping in controller, but it still alive
I work in Idea 12.0.4
The problem was in the cache/IDE.
Class file is not updated when I deploy project.
First time i get trouble like this. Just restart IDE and clean tomcat webapps folder(delete my project files from here).
Now everything works as expected.

Spring Controller's URL request mapping not working as expected

I have created a mapping in web.xml something like this:
<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>/about/*</url-pattern>
</servlet-mapping>
In my controller I have something like this:
import org.springframework.stereotype.Controller;
#Controller
public class MyController{
#RequestMapping(value="/about/us", method=RequestMethod.GET)
public ModelAndView myMethod1(ModelMap model){
//some code
return new ModelAndView("aboutus1.jsp",model);
}
#RequestMapping(value="/about", method=RequestMethod.GET)
public ModelAndView myMethod2(ModelMap model){
//some code
return new ModelAndView("aboutus2.jsp",model);
}
}
And my dispatcher-servlet.xml has view resolver like:
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
To my surprise: request .../about/us is not reaching to myMethod1 in the controller. The browser shows 404 error. I put a logger inside the method but it isn't printing anything, meaning, its not being executed.
.../about works fine! What can be the done to make .../about/us request work? Any suggestions?
You need to use #RequestMapping(value="/us", method=RequestMethod.GET) or you need to request about/about/us
Since you have mapped "/about" in your web.xml, the url it will pass will be like this www.xyz.com/about/*
As your configuration says it will work for
www.xyz.com/about/about/us
www.xyz.com/about/about
In order to to work properly either use
/* in web.xml instead of /about
or change the controller's endpoint to
#RequestMapping(value="/us", method=RequestMethod.GET)
#RequestMapping(value="/", method=RequestMethod.GET)
Okay I got the thing working, here are things I added in the dispatcher-servlet.xml:
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true" />
</bean>

Resources