Spring mvc controller handling all request and should not do that - spring

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")
...
}

Related

Spring URI - Controller Mapping

I have a controller mapping that worked before I put in Spring Security. I am learning MVC and Spring.
Now I get a PageNotFoundException saying that path cannot be found. If you see my controller it maps to /user and the method to get the data in /list.
I'm not sure what the issue is. Any help would be useful.
Here is the information:
mvc-dispatcher-servlet.xml
<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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- Bean to show you Di in GAE, via Spring, also init the UserController -->
<!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
-->
<context:component-scan base-package="com.principalmvl.lojackmykids">
<context:include-filter type="regex" expression="(service|constroller)\..*"/>
</context:component-scan>
<!-- Enables JSR-303 -->
<mvc:annotation-driven/>
<context:annotation-config />
<bean class="com.google.appengine.api.users.UserServiceFactory"
factory-method="getUserService" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
web.xml
<?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"
version="2.5">
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml /WEB-INF/applicationContext-security.xml</param-value>
</context-param>
<sessions-enabled>true</sessions-enabled>
<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>
<filter>
<filter-name>datastoreFilter</filter-name>
<filter-class>org.slim3.datastore.DatastoreFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>datastoreFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>profile</web-resource-name>
<url-pattern>/profile/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>admin</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
UserController.java
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.GET)
public String getAddUserPage(ModelMap model) {
return "add";
}
// get all users
#RequestMapping(value = "/list", method = RequestMethod.GET)
#ResponseBody
public List<Contact> listCustomer( ModelMap model) {
List<Contact> users = Datastore.query(Contact.class).asList();
model.addAttribute("userList", users);
return users;
}
}
LoginController.Java [This is the first controller that gets called]
#Controller
public class LoginController {
private static final Logger log = Logger.getLogger(LookupUserServlet.class
.getName());
#RequestMapping(value = "/", method = RequestMethod.GET)
public String landing() {
return "landing";
}
#RequestMapping(value = "/home.jsp", method = RequestMethod.GET)
public String home() {
return "home";
}
#RequestMapping(value = "/disabled.jsp", method = RequestMethod.GET)
public String disabled() {
return "disabled";
}
#RequestMapping(value = "/logout.jsp", method = RequestMethod.GET)
public void logout(HttpServletRequest request, HttpServletResponse response)
throws IOException {
request.getSession().invalidate();
String logoutUrl = UserServiceFactory.getUserService().createLogoutURL(
"/loggedout.jsp");
response.sendRedirect(logoutUrl);
}
#RequestMapping(value = "/loggedout.jsp", method = RequestMethod.GET)
public String loggedOut() {
return "loggedout";
}
#RequestMapping("/ListUsers")
public String ListUser() {
return "users/ListUsers";
}
#RequestMapping("/SendAll")
public String SendAll() {
return "sendmessage/SendAll";
}
In my ListUsers method should I redirect to the controller called UserController?
Your list has extra /
#RequestMapping(value = "/list/", method = RequestMethod.POST)
Change it to
#RequestMapping(value = "/list", method = RequestMethod.POST)
This is on assumption that your form being submitted is pointing to "/list"
So I moved the URI mapping to my controller called LoginController and the request worked. My question is now, why is my UserController not getting picked up. I have the context base-scan scanning in all the base packages and my controller.
Does anyone have an idea?
Upon more investigation. I believe that Eclipse did something to the Java class. When I looked at the Java class and how Eclipse annotates it, it did not have a corresponding "twisty" that shows a contractor of the class.
I created another Java class and added the code and it worked appropriately.

The requested resource is not available error in spring mvc project

I got an error as follows :
Status report
message: /SBC/loginform.html
description :The requested resource is not available.
dispatcher-servlet.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OpticareVisionHouse</display-name>
<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>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/resources/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
-------------------------------------------------
LoginController.java
#Controller
#RequestMapping("loginform.html")
public class LoginController {
#Autowired
public LoginService loginService;
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
System.out.print("controller calls1");
return "loginform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map model) {
System.out.print("controller calls2");
if (result.hasErrors()) {
return "loginform";
}
/*
String userName = "UserName";
String password = "password";
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUserName().equals(userName)
|| !loginForm.getPassword().equals(password)) {
return "loginform";
}
*/
boolean userExists = loginService.checkLogin(loginForm.getUserName(),
loginForm.getPassword());
if(userExists){
model.put("loginForm", loginForm);
return "loginsuccess";
}else{
result.rejectValue("userName","invaliduser");
return "loginform";
}
}
------------------------------------------------
index.jsp
<% response.sendRedirect("loginform.html"); %>
------------------------------------------------
index.jsp is there at webContent.
loginform.jsp is at webContent->web-Inf ->Views
Your dispatcherServlet is mapping urls like: /forms/* to the spring servlet.
You are requesting a url like: /SBC/loginform.html
This request will never go to the spring servlet. You have to access: /{your app context}/forms/loginform.html in order to go to the spring url mapped. Your app context seems to be "SBC", so it will be something like: /SBC/forms/loginform.html
Another way is change the Servlet mapping to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This way, every request on your app context /SBC/* will be routed to the spring servlet.
With this configuration, you should be able to access your controller with: /SBC/loginform.html

How to load the data in index page using spring mvc?

I tried couple of Tutorial in Spring-MVC to load the data in index page without using ajax call means before loading the index page I want to get the data from server and load the data into the index page.but did not get proper answer.
Finally after couple of try i got the answer.here is my code.
web.xml
<display-name>SpringTest</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
My Controller
#Controller
public class WebController {
#Autowired
private EmployeeService empService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
List<Employee> empList = empService.getAllEmployee();
Collections.sort(empList, new EmployeeSortById());
ModelAndView modelMap = new ModelAndView("index","employeeList", empList);
System.out.println("Calling controller");
return modelMap;
}
}
spring-context.xml
<context:component-scan base-package="com.app.controller,com.app.dao.impl,com.app.service.impl" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>

Spring MVC : Ambiguous mapping found

I couldn't understand why the following gives an ambiguous mapping.
a. The controller class
#Controller
#RequestMapping("/employees")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String get(Model model) {
return "xx";
}
}
Console output:
java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'org.tutorial.spring.controller.EmployeeController#0' bean method
public java.lang.String org.tutorial.spring.controller.EmployeeController.get(org.springframework.ui.Model)
to {[/employees/new],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'employeeController' bean method
public java.lang.String org.tutorial.spring.controller.EmployeeController.get(org.springframework.ui.Model) mapped.
It says method has already been mapped.
How so?
b. web.xml
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
c. spring.xml
<context:annotation-config />
<context:component-scan base-package="org.tutorial.spring" />
<mvc:annotation-driven />
<bean class="org.tutorial.spring.controller.EmployeeController" />
Try removing the bean element
<bean class="org.tutorial.spring.controller.EmployeeController" />
from your XML. I suspect this is causing you problems because
<context:component-scan base-package="org.tutorial.spring" />
will scan your package, and identify EmployeeController as a bean, due to its annotations. Then, afterwards, you are manually adding the same bean.

setting fullpath in controller

i have developed a spring application. all requests are dispatching to controllers (i have 2 controllers in my app) so web.xml is like below
in web.xml
<servlet-mapping>
<url-pattern>/*</url-pattern>
aaa controller
#Controller
#RequestMapping("/aaa")
bbb controller
#Controller
#RequestMapping("/bbb")
but now i need to add some jsp pages into my project since the "/*" in web.xml my jsp pages are not found. so i have change the servlet-mapping like below;
in web.xml
<servlet-mapping>
<url-pattern>/aaa/*</url-pattern>
<url-pattern>/bbb/*</url-pattern>
aaa controller
#Controller
#RequestMapping("/")
bbb controller
#Controller
#RequestMapping("/")
but i do not want to use this approach since i can access xxx servlet in aaa controler like /bbb/xxx.
so is there any alternative solution, for example can i set full path in controller or anything?
thanks in advance...
You need to pass jsp through the server as well.
You can map it as html extension
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
In example-servlet.xml just add the following jsp resolver
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
and then use ModelAndView Object in your controllers:
#Controller
#RequestMapping(value="/aaa")
public class aaaController{
#RequestMapping(value="/aaa.html", method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView mv = new ModelAndView("aaa");
return mv;
}
}
#Controller
#RequestMapping(value="/bbb")
public class aaaController{
#RequestMapping(value="/bbb.html", method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView mv = new ModelAndView("bbb");
return mv;
}
}
In that case first controller will return /aaa.jsp as you your model andView when you hit /aaa/aaa.html
and second controller will return /bbb.jsp as you your model and View when you hit /bbb/bbb.html
Hope it helps.

Resources