I'm working on an open source projet and i have issues with my application.
When multiple users use the app, one users can get another one's data ( the server response).
my beans are request and session scoped and my controller request scoped.
When starting tomcat, beans are created 3x times.
I've read lot of documentations and try playing with scopes and nothing.
I must be missing something. Thanks for your help.
My controller:.
#Controller
#Scope("request")
public class SpinalToolboxWebController {
#Autowired
private FileOperationsService fileOperationsService;
#Autowired
private ServerResponse serverResponse;
#Autowired
private SoftwareCommunicationService softwareCommunicationService;
#Autowired
private StringBuffer stringBuffer;
#Autowired
private UserEnvironmentService userEnvironmentService;
#RequestMapping(value = "/")
public ModelAndView home(){
System.out.println("Passing throught home controller");
return new ModelAndView(SpinalToolBoxWebConstants.VIEW_HOME, "result", "command submitted : ");
}
#RequestMapping(value="/upload", method = RequestMethod.POST, produces="application/json")
public #ResponseBody
ServerResponse handleUploadedFiles(#RequestParam(value = "file") MultipartFile file,
#RequestParam(value="token") String token)throws IOException {
System.out.println("Passing throught upload controller");
if(!fileOperationsService.isUploadedFileExtensionAllowed(file.getOriginalFilename()))
{
serverResponse.setUndefinedResponse();
return serverResponse;
}
if(fileOperationsService.uploadFile(file, token)){
serverResponse.setResponse(file, softwareCommunicationService.generateRawAndHeader(file));
}
else{
serverResponse.setUndefinedResponse();
}
return serverResponse;
}
}
Here is my java config file:
#Configuration
public class SpinalToolBoxWebConfig {
#Value("${uploadPath}") private String uploadPathFromPropertyFile;
//Resolve view name to jsp
#Bean
ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/view/");
resolver.setSuffix(".jsp");
/*resolver.setExposeContextBeansAsAttributes(true);
resolver.setExposedContextBeanNames("configProperties");*/
return resolver;
}
#Bean
#Scope("request")
#ScopedProxy
public FileOperationsController fileOperationsController(){
return new FileOperationsController();
}
#Bean
#Scope("request")
#ScopedProxy
public LogController logController() {return new LogController();}
#Bean
#Scope("request")
#ScopedProxy
public ServerResponse serverResponse(){return new ServerResponse();}
#Bean
#Scope("request")
#ScopedProxy
public SoftwareCommunicationController softwareCommunicationController() {return new SoftwareCommunicationController();}
#Bean
#Scope("prototype")
public CommonsMultipartResolver multipartResolver() throws java.io.IOException{
Resource fileSystemResource = new FileSystemResource(uploadPathFromPropertyFile);
System.out.println(uploadPathFromPropertyFile);
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setUploadTempDir(fileSystemResource);
commonsMultipartResolver.setMaxUploadSize(-1); //no limit to file upload size
return commonsMultipartResolver;
}
#Bean
#Scope("request")
#ScopedProxy
public StringBuffer stringBuffer(){ return new StringBuffer();}
#Bean
#Scope("session")
#ScopedProxy
public UserEnvironment userEnvironment(){
return new UserEnvironment();
}
#Bean
#Scope("request")
#ScopedProxy
public UserEnvironmentController userEnvironmentController(){return new UserEnvironmentController(); }
}
Here is my servlet-context.xml file:
<?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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<util:properties id="configProperties" location="WEB-INF/config.properties" />
<context:property-placeholder properties-ref="configProperties" />
<context:component-scan base-package="spinalToolBoxWeb"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="${resources}" />
<mvc:resources mapping="/external/**" location="file:///${uploadPath}" />
</beans>
Here is my web xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>spinalToolBoxServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spinalToolBoxServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spinalToolBoxServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener> </web-app>
Related
I am trying to autowire an object using component-scan in my restFul Webservice. But getting Nullpointer exception when userDao object is used.
I dont want to use Spring MVC or spring boot. Just want to simply inject the dependency using component-scan. Please help!!!
UserDao.java
#Component
public class UserDao {
public List<User> getAllUsers(){
//return a list
}
}
UserService.java
#Component
#Path("/UserService")
public class UserService {
#Autowired
private UserDao userDao;
#PostConstruct
public void initialize() {
System.out.println("userDao object: " + userDao);
}
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers(){
return getUserDao().getAllUsers();
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
applicationContext.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:aop = "http://www.springframework.org/schema/aop"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<context:annotation-config/>
<context:component-scan base-package="com.rest"/>
<aop:aspectj-autoproxy/>
</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>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
You will need to define a bean in your applicationContext.xml file. Spring container initializes this bean when the application is started.
eg.
<bean id="userDAO" class="your.package.name.UserDAO">
<!-- In case if you use hibernate -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
As an analogy, you can think of this as spring is doing UserDAO userDAO = new UserDAO(); for you.
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!!!!
I am starting to use Spring Security. I've always implement my own security. So this is new for me. I've followed few tutorials. I've read even Pro Spring Security Book (unfortunatelly everythink was configured with xml).
I would like to write Rest Api base on Spring and Spring Security. I will have to main routes to my api. First is for anonymous users, and this goes as follow:
http://localhost:8080/cms/services/anonymous/**
The second url route is for authenticated users:
http://localhost:8080/cms/services/authenticated/**
When I hit url like this:
http://localhost:8080/cms/services/authenticated/testService/getInfo
I should get http answer 401 Unauthorized. But in my current project I am getting 200 Ok. What I am doing wrong?
Here is my config:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
#EnableWebMvc
#Configuration
#ComponentScan("pl.korbeldaniel.cms.server")
#Import({ SecurityConfig.class })
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource getMessageSource() {
ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
resource.setBasename("classpath:messages");
resource.setDefaultEncoding("UTF-8");
return resource;
}
#Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(new MappingJackson2HttpMessageConverter());
}
}
#Configuration
#ComponentScan("pl.korbeldaniel.cms.server")
#EnableWebSecurity
// #EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableGlobalMethodSecurity(securedEnabled = true)
#PropertySource("classpath:jdbc.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
Environment env;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("temporary").password("temporary").roles("ADMIN").and().withUser("user").password("userPass").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().//
antMatchers("/cms/services/authenticated/**").authenticated().//
antMatchers("/cms/services/anonymous/**").anonymous().and().//
csrf().disable();
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
}
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
<?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">
<!-- Name the application -->
<display-name>Rest GWT</display-name>
<description>This is web-project for cms</description>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/action-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>cms.html</welcome-file>
</welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" 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/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">
<!-- Scans the classpath of this application for #Components to deploy as
beans -->
<context:component-scan base-package="pl.korbeldaniel.cms" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
</beans>
<?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"
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-3.0.xsd">
<!-- registers all of Spring's standard post-processors for annotation-based configuration -->
<context:annotation-config />
</beans>
Please help.
You should register your SecurityConfig in AbstractAnnotationConfigDispatcherServletInitializer, like following:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I am learning/developing website in JSP with Sping MVC. The problem now I am facing is that when I try to visit url "localhost/site/about///" it shows default home page, if I go to "localhost/site" it shows home page and if I go to "localhost/about" it shows about page. So I don't know how to throw error page if someone tries to access page with any single forward slash. I mean if I try to access "localhost/site/about/" or "localhost/site/about///" I want my app to throw 404 error page.
Here is my web.xml code
<?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>Test</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>/</url-pattern>
</servlet-mapping>
</web-app>
My dispatcher-servlet.xml file's codes are
<?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.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:component-scan base-package="com.test.router" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsps/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My router file's codes are
package com.test.router;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class Router {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView homePage(){
ModelAndView model = new ModelAndView("HomePage");
model.addObject("title", "Welcome to home page");
model.addObject("msg", "This is the home page.");
return model;
}
#RequestMapping(value = "/about", method = RequestMethod.GET)
public ModelAndView aboutPage(){
ModelAndView model = new ModelAndView("AboutPage");
model.addObject("title", "About Test website.");
return model;
}
#RequestMapping(value = "/accounts/login", method = RequestMethod.GET)
public ModelAndView loginPage(){
ModelAndView model = new ModelAndView("accounts");
model.addObject("title", "Login here to access Test Website.");
model.addObject("pageTitle", "Login page.");
return model;
}
#RequestMapping(value = "/accounts/signup", method = RequestMethod.GET)
public ModelAndView signupPage(){
ModelAndView model = new ModelAndView("accounts");
model.addObject("title", "Signup here to join and explore Test Website.");
model.addObject("pageTitle", "Signup page.");
return model;
}
#RequestMapping(value = "/accounts/logout", method = RequestMethod.GET)
public ModelAndView logoutPage(){
ModelAndView model = new ModelAndView("accounts");
model.addObject("title", "Logging you out securely.");
model.addObject("pageTitle", "Logout page.");
return model;
}
}
So can anyone tell me how can I stop showing default home page after single or multiple forward slashes? Thank you for help.
If you are getting exception in the code then for specific exceptions you can rendor specific views by using exception resolver.
You can have a fallback method to show the error page as follows:
#RequestMapping(value = "*")
#ResponseBody
public String errorPage() {
return "Error page";
}
EDIT:
Else you can use regular expression to handle multiple forward slashes at the end:
#RequestMapping("{multipleForwardSlashes:[/]{2,}$}")
public String errorPage(#PathVariable String multipleForwardSlashes) {
return "Error page";
}
My application, which make use of Spring Security, is crashing during the startup. Tracking the execution of the application, I could verify the error is happening in method onStartup from class MainWebAppInitializer:
public class MainWebAppInitializer implements WebApplicationInitializer {
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
#Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.spring.web.config");
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("horariolivreapp", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
More specificly, the error occurs in the line
appServlet.setLoadOnStartup(1)
where a NullPointerException is triggered. Follow it is my configuration files, for reference:
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_3_0.xsd"
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>HorarioLivre</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>horariolivreapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>horariolivreapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.web.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<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>
</web-app>
horariolivreap-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"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd">
<context:component-scan base-package="com.horariolivreapp.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
webSecurityConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<http use-expressions="true">
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
login-page='/form_login.html'
login-processing-url="/usuario_login.html"
default-target-url="/usuario_start.html"
authentication-failure-url="/form_login"
always-use-default-target="true"/>
<logout logout-success-url="/login.html" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Looking in this files, someone can find the reason for this problem?
UPDATE 1
This is my Controller (DispatcherServlet) class:
package com.horariolivreapp.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.horariolivreapp.core.Sessao;
import com.horariolivreapp.data.UsuarioDAO;
#Controller
public class HorarioLivreController {
private Sessao sessao;
#RequestMapping("/cadastra_evento")
public ModelAndView cadastra_evento() {
return null;
}
#RequestMapping(value="/listagem_evento", method=RequestMethod.GET)
public ModelAndView listagem_evento() {
return null;
}
#RequestMapping("/cadastra_horario")
public ModelAndView cadastra_horario() {
return null;
}
#RequestMapping("/listagem_horario")
public ModelAndView listagem_horario() {
return null;
}
#RequestMapping("/cadastra_usuario")
public ModelAndView cadastra_usuario() {
return null;
}
#RequestMapping("/listagem_usuario")
public ModelAndView listagem_usuario() {
return null;
}
#RequestMapping("/cadastra_tipo")
public ModelAndView cadastra_tipo() {
return null;
}
#RequestMapping("/cadastra_campo")
public ModelAndView cadastra_campo() {
return null;
}
#RequestMapping("/cadastra_autorizacao")
public ModelAndView cadastra_autorizacao() {
return null;
}
#RequestMapping("/usuario_perfil")
public ModelAndView usuario_perfil() {
return null;
}
#RequestMapping("/usuario_config")
public ModelAndView usuario_config() {
return null;
}
#RequestMapping(value="/usuario_login", method=RequestMethod.POST)
public ModelAndView usuario_login(#RequestParam("j_username") String username, #RequestParam("j_password") String password) {
UsuarioDAO usuario = new UsuarioDAO(username, password);
if(usuario.getUsuario() != null) {
this.sessao = new Sessao(usuario.getUsuario());
}
return new ModelAndView("usuario_start","usuario",usuario.getUsuario());
}
#Configuration
#ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}
}
An NPE at that point means that appServlet is null, which in turn means that sc.addServlet(...) returned null.
The Javadoc for addServlet says this:
"Returns: a ServletRegistration object that may be used to further configure the given servlet, or null if this ServletContext already contains a complete ServletRegistration for a servlet with the given servletName or if the same servlet instance has already been registered with this or another ServletContext in the same container."
Now you are instantiating the Servlet object at that point, so it cannot have previously been registered. But there could be another Servlet with the same name ... and that's the probable immediate cause of the problem.
And in fact, it looks like you have already registered a servlet called "horariolivreapp" by declaring it in the web.xml file.