not able to get value in view from controller in spring - 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

Related

Mapping Controllers

What is wrong?
I was wrote two controllers but don't understand what is wrong.
Don't know how to make correct for working both controller correct.
Type Exception Report
Message Servlet.init() for servlet [mvc-dispatcher] threw exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [mvc-dispatcher] threw exception
rg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'bookController' bean method
public java.lang.String com.jackson.BookController.editBook(int,org.springframework.ui.Model)
to {[/edit/{id}],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'authorController' bean method
public java.lang.String com.jackson.AuthorController.editAuthor(int,org.springframework.ui.Model) mapped.
package com.jackson;
#Controller
public class AuthorController {
private AuthorService authorService;
#Autowired(required = true)
#Qualifier(value = "authorService")
public void setBookService(AuthorService authorService) {
this.authorService = authorService;
}
#RequestMapping
(value = "authors", method = RequestMethod.GET)
public String listAuthors(Model model){
model.addAttribute("author", new Author());
model.addAttribute("listAuthors", this.authorService.list());
return "authors";
}
#RequestMapping
(value = "authors/add", method = RequestMethod.POST)
public String addAuthor(#ModelAttribute("author") Author author){
if(author.getId() == 0){
this.authorService.addAuthor(author);
}else {
this.authorService.updateAuthor(author);
}
return "redirect:/authors";
}
#RequestMapping("/remove/{id}")
public String removeAuthor(#PathVariable("id") int id){
this.authorService.removeAuthor(id);
return "redirect:/authors";
}
#RequestMapping("/edit/{id}")
public String editAuthor(#PathVariable("id") int id, Model model){
model.addAttribute("author", this.authorService.getAuthorById(id));
model.addAttribute("listBooks", this.authorService.list());
return "authors";
}
#RequestMapping("authordata/{id}")
public String authorData(#PathVariable("id") int id, Model model){
model.addAttribute("author", this.authorService.getAuthorById(id));
return "authordata";
}
}
In my opinion all code working right but still understand whats wrong
package com.jackson;
#RestController
public class BookController {
private BookService bookService;
#Autowired(required = true)
#Qualifier(value = "bookService")
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
#RequestMapping(value = "books", method = RequestMethod.GET)
public String listBooks(Model model){
model.addAttribute("book", new Book());
model.addAttribute("listBooks", this.bookService.listBooks());
return "books";
}
#RequestMapping(value = "/books/add", method = RequestMethod.POST)
public String addBook(#ModelAttribute("book") Book book){
if(book.getId() == 0){
this.bookService.addBook(book);
}else {
this.bookService.updateBook(book);
}
return "redirect:/books";
}
#RequestMapping("/remove/{id}")
public String removeBook(#PathVariable("id") int id){
this.bookService.removeBook(id);
return "redirect:/books";
}
#RequestMapping("edit/{id}")
public String editBook(#PathVariable("id") int id, Model model){
model.addAttribute("book", this.bookService.getBookById(id));
model.addAttribute("listBooks", this.bookService.listBooks());
return "books";
}
#RequestMapping("bookdata/{id}")
public String bookData(#PathVariable("id") int id, Model model){
model.addAttribute("book", this.bookService.getBookById(id));
return "bookdata";
}
}
In my opinion all code working right but still understand whats wrong
mvc-dispacther-servlet.xml
<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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.jackson"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
// database config
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.jackson.Book</value>
<value>com.jackson.Author</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!--BookDao and BookService beans-->
<bean id="bookDao" class="com.jackson.BookDao">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<bean id="bookService" class="com.jackson.BookService">
<property name="bookDao" ref="bookDao"/>
</bean>
<bean id="authorDao" class="com.jackson.AuthorDao">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<bean id="authorService" class="com.jackson.AuthorService">
<property name="authorDao" ref="authorDao"/>
</bean>
<context:component-scan base-package="com.jackson"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
web.xml
<web-app 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>com.jackson.Book Manager</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Your controllers have conflict mapping methods. Don't declare same request mapping method on different controllers.
BookController needs to have #Controller instead of #RestController.

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

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>

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 controller handling all request and should not do that

I have two controllers:
UserController and AdminController.
The AdminController is handling all requests that have not created. Also handle the request to access to my resources.
Also I'm using spring-security and maven to compile all.
Examples:
Request: .../appName/login --> return login view.
Request: .../appName/home --> return home view.
Request: .../appName/fahsjhgasghdjfg --> return admin view.
Request: .../appName/dasjdha/fhfashjfs --> return admin view.
Request: .../appName/resources/css/one.css --> return admin view.
If I remove the AdminController and create a new controller with name ExamplefasjkasController it happens the same.
Code:
Controllers:
#Controller
public class AdminController {
#RequestMapping(name = "/panel")
public ModelAndView adminPanel() {
return new ModelAndView("admin");
}
}
#Controller
public class UserController extends GenericController {
#Autowired
private IUserService userService;
#RequestMapping(value = { "/", "/home" })
public ModelAndView home(HttpServletRequest request, Principal principal) {
ModelAndView model = new ModelAndView(Name.VIEW_HOME);
model.setViewName(Name.VIEW_HOME);
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(HttpServletRequest request,
#RequestParam(value = Name.PARAM_ERROR, required = false) String error,
#RequestParam(value = Name.PARAM_LOGOUT, required = false) String logout) {
ModelAndView model = new ModelAndView();
model.setViewName(Name.VIEW_LOGIN);
if (error != null) {
addError(model, getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
}
if (logout != null) {
addInfo(model, Message.INFO_USER_LOGOUT);
}
return model;
}
}
In the AdminController I try to get Request with
#Controller
#RequestMapping(name = "/admin"}
public class AdminController {
#RequestMapping(name = "/panel")
...
}
But I get an exception:
javax.servlet.ServletException: No adapter for handler [com.base.controller.AdminController#3f114da7]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
XMLs:
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-mvc-dispatcher.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</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>
/WEB-INF/spring/spring-database.xml,
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<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>
spring-mvc-dispatcher.xml
<mvc:resources mapping="/web_resources/bower_components/**" location="classpath:/web_resources/bower_components/" />
<mvc:resources mapping="/web_resources/layouts/**" location="classpath:/web_resources/layouts/" />
<mvc:resources mapping="/web_resources/elements/**" location="classpath:/web_resources/elements/" />
<context:component-scan base-package="com.base.*" />
<mvc:annotation-driven />
<context:annotation-config />
<import resource="spring-messages.xml" />
<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>
I could share the entire application if someone request.
Thanks in advance and best regards.
You have to fix your request mapping as below:
#Controller
#RequestMapping(value = "/admin"}
public class AdminController {
#RequestMapping(value = "/panel")
...
}

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.

Resources