Getting a 404 in Spring RESTful controller - java

I am trying to do a restful service in spring mvc. This is my controller code,
#Controller
#RequestMapping("/manageuser")
public class ManageUserController {
#RequestMapping(value = "/deleteuser/{user}", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
protected void deleteUser(#PathVariable String user, ModelMap model) {
System.out.println(user);
}
#RequestMapping(value = "/adduser/{user}", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
protected void addUser(#PathVariable String user, ModelMap model) {
System.out.println(user);
}
}
My manageuser-servelt.xml
<context:component-scan base-package="com.example.web" use-default-filters="false"
>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
My web.xml content,
<servlet>
<servlet-name>manageuser</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:manageuser-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>manageuser</servlet-name>
<url-pattern>/manageuser</url-pattern>
</servlet-mapping>
I am getting a 404 if I navigate to localhost/manageuser/adduser/Barney. What am I doing wrong here? Is this the right approach for RESTful services using spring-mvc?

Does "the System.out.println(user)" display the user ? If not, you have a problem in your mapping.
Check another Blog here : http://www.breathejava.com/restful-web-service-tutorial-spring-xml/.

Related

SEVERE: Servlet.init() call for Servlet [appServlet] caused an exception

While implementing CRUD with a spring, this error occurred and has not been able to proceed with CRUD for several hours...
"Line 7 of the xml document of the servlet context resource [/web-inf/spring/appservlet/slaplet-slap.xml] is invalid."
Even if line 7 is erased, line 6 is an error and line 5 is an error if erased once again, so I don't think this is an empty tag problem.
Just in case, I'll put the controller and dao.
I'm worried that it'll be uncomfortable to watch. sorry..
help me!!
Controller
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
}
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
DAO
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure --> <!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up
static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/plugins/**"
location="/resources/plugins/" />
<resources mapping="/dist/**" location="/resources/dist/" /> <!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan
base-package="com.cameldev.httpsession" />
</beans:beans>
root-context.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"
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">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy" />
<property name="url"
value="jdbc:log4jdbc:mysql://127.0.0.1:3306/injo?serverTimezone=UTC&useSSL=false" />
<property name="username" value="root" />
<property name="password" value="howang12" />
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:/mybatis-config.xml" />
<property name="mapperLocations"
value="classpath:mappers/**/*Mapper.xml" />
</bean>
<bean id="sqlSession"
class="org.mybatis.spring.SqlSessionTemplate"
destroy-method="clearCache">
<constructor-arg name="sqlSessionFactory"
ref="sqlSessionFactory" />
</bean>
<context:component-scan base-package="com.cameldev.httpsession" />
</beans>
web.xml
<?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 https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param> <!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Processes application requests -->
<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>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'

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!!!!

Problems with Spring Security 4 and REST, does not display HTML files

I have a problem with my proyect, I've tried to configure Spring Security 4 with Spring REST, but there is a problem when I try to access with any context.
Here is my project structure:
Inside of "views" are my html pages.
And here is my spring configuration.
<import resource="classpath:applicationContext-business.xml"/>
<mvc:annotation-driven />
<security:http auto-config="true" >
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/home" access="permitAll" />
<security:form-login login-page="/iniciar_sesion"
username-parameter="email"
password-parameter="password"
authentication-failure-url="/Access_Denied" />
<security:csrf/>
</security:http>
<context:component-scan base-package="turing.solutions.dy.web" >
<context:include-filter type="regex" expression=".*\.(.)*"/>
<context:exclude-filter type="regex" expression="security"/>
</context:component-scan>
<bean id="customUserDetailsService" class="turing.solutions.dy.web.security.CustomUserDetailService" />
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService"/>
</security:authentication-manager>
And my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dy</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dy</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>
10
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
And this is my RestController:
#RestController
public class LoginController {
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage() {
System.out.println("Redirect");
return "index";
}
#RequestMapping(value="iniciar_sesion",method = RequestMethod.GET)
public String iniciarSession(ModelMap model){
model.put("login", "log");
return "iniciar_sesion";
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> login() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("login", "ok");
return map;
}
#RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "accessDenied";
}
private String getPrincipal() {
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}
Ant this is my CustomUserDetailService
#Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {
#Autowired
private UsuariosService usuariosService;
#Override
public UserDetails loadUserByUsername(String correo) throws UsernameNotFoundException {
Usuarios usuario = this.usuariosService.findByCorreo(correo);
if (usuario == null) {
throw new UsernameNotFoundException("El usuairo " + correo + " no existe, favor de verificar");
}
return new User(usuario.getEmail(), usuario.getPassword(), usuario.getActivo(), true, true, true, getGrantedAuthorities(usuario));
}
private List<GrantedAuthority> getGrantedAuthorities(Usuarios usuario) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Roles rol : usuario.getRolesList()) {
System.out.println("Usuario " + usuario.getEmail() + " ROl" + rol.getDescRol().toUpperCase());
authorities.add(new SimpleGrantedAuthority("ROLE_" + rol.getDescRol().toUpperCase()));
}
return authorities;
}
}
When I try to access to the URL "http://localhost:9080/DespreocupateYA/home" I see this
But I should see this
So,my question is: Why i can't see the html pages in my project? I've searched and I found many Spring configurations, but I've not been able to solve the problem.
My Server is an Apache Tomcat 8.0.28.
I hope you can help me, Thanks.
Change your #RestController annotation to #Controller and it will work properly.
Here are docs explaining the difference between this two annotations
Morover when you say RestController you mean a Controller wich handle some data like JSON objects. Here you need a simple Controller to handle html views.
EDIT
You didn't mention what kind of view rendering engine you are using, this is example configuration for jsp
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
And this to your spring conifguration file, make sure you declare "http://www.springframework.org/schema/beans" name space so you can use bean definition

Spring post redirects to access-denied while get works

I apologize for a somewhat duplicate post, I asked a question about this yesterday however I did not do a good job of stating the problem and because of this the feedback was not useful. I have since learned more about the problem and can put it in a more clear and concise way which will hopefully help solve this.
Whenever I try to post to a page the controller maps the url to the access-denied-handler as specified by mvc-dispatch-servlet.xml. If I try to get to a page then it hits the correct #requestmapping and everything is ok.
I have tried adding
<intercept-url pattern="/pages/ReceiveFile" access="permitAll"/>
which does nothing.
I have just recently narrowed this problem down to
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
which seems to be blocking the post operations. If I change this to /pages/* then I can post to a page that is /ReceiveFile because it is mapped that way in web.xml. This skips the main controller altogether. With that setting if I try to go to pages/ReceiveFile it still goes through the controller and goes to the 403 page. I don't believe bypassing my controller with all post operations is a good permanent solution.
How do I allow these post operations to go through?
Thanks!
Main Controller.java
some code cut to reduce unnecessary length
#Controller
public class MainController {
String URLroot = "pages/";
#PreAuthorize("hasRole('_discover')")
#RequestMapping(value = {"/discover/**" }, method = RequestMethod.GET)
public ModelAndView discover(HttpServletRequest request) {
StringBuffer mapping = request.getRequestURL();
String URLoffset = getURLoffset(mapping);
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Login Form - Database Authentication");
model.addObject("message", "This is default page no longer!");
model.setViewName(URLoffset);
return model;
}
/**
* Upload single file using Spring Controller
*/
#RequestMapping(value = "/ReceiveFile", method = {RequestMethod.POST,RequestMethod.GET})
public ModelAndView test(){
//Do useful things which require post.....
ModelAndView model = new ModelAndView();
model.setViewName("springtest");
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage(HttpServletRequest request) {
StringBuffer mapping = request.getRequestURL();
String URLoffset = getURLoffset(mapping);
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Login Form - Database Authentication");
model.addObject("message", "This page is for ROLE_ADMIN only!");
model.setViewName(URLoffset);
return model;
}
#RequestMapping(value = "/signout", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("signout");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
//for 403 access denied page
#RequestMapping(value = "/403", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView accesssDenied() {
ModelAndView model = new ModelAndView();
//check if user is logged in
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(auth.getName());
model.addObject("username", auth.getName());
}
model.setViewName("/403");
return model;
}
/**
* Upload single file using Spring Controller
*/
#RequestMapping(value = "/uploadFile2", method = {RequestMethod.POST,RequestMethod.GET})
public #ResponseBody
String uploadFileHandler(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
instance.debug("FileUploadController" + " uploadFileHandler", "Server File Location=" + serverFile.getAbsolutePath());
return "You successfully uploaded file=" + name;
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
}
mvc-dispatch-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mkyong.*" />
<!-- Currently not working. Made a work around by having resources at /resources and pages at /pages -->
<mvc:resources location="/resources/" mapping="/resources/" />
<!-- also add the following beans to get rid of some exceptions -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize">
<value>100000</value>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mkyong.*" />
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<!-- login page must be available to all. The order matters, if this is after something which secures the page this will fail. -->
<!-- <intercept-url pattern="/SignupUserServlet" access="permitAll"/> -->
<intercept-url pattern="/pages/ReceiveFile" access="permitAll"/>
<intercept-url pattern="/pages/fileUpdate2" access="permitAll"/>
<intercept-url pattern="/pages/login" access="permitAll" />
<intercept-url pattern="/pages/admin/**" access="hasRole('_admin')" />
<intercept-url pattern="/pages/trade/**" access="hasRole('_trader')" />
<intercept-url pattern="/pages/discover/**" access="hasRole('_users')" />
<!-- access denied page -->
<access-denied-handler error-page="/pages/403" />
<form-login
login-page="/pages/login"
default-target-url="/pages/common/redirectportal"
authentication-failure-url="/pages/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-url="/pages/logout" logout-success-url="/pages/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Select users and user_roles from database -->
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider"/>
<!--<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select email,pwhash, enabled from users where email=?"
authorities-by-username-query=
"select email, groupname from usergroups where email =? " />
</authentication-provider> -->
</authentication-manager>
</beans:beans>
web.xml
<web-app id="WebApp_ID" 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">
<!-- Spring MVC -->
<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>
<servlet-name>InitServlet</servlet-name>
<servlet-class>servlet.InitServlet</servlet-class>
<init-param>
<param-name>configfile</param-name>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>servlet.admin.AdminServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>servlet.user.UserServlet</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet>
<servlet-name>SignupUserServlet</servlet-name>
<servlet-class>servlet.user.SignupUserServlet</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet>
<servlet-name>ReceiveFile</servlet-name>
<servlet-class>servlet.user.ReceiveFile</servlet-class>
<load-on-startup>6</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/pages/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/AdminServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SignupUserServlet</servlet-name>
<url-pattern>/SignupUserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ReceiveFile</servlet-name>
<url-pattern>/ReceiveFile</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-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<!-- 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>
I'm not 100% sure, but I think it's this line of configuration that's causing the problem in the spring-security.xml:
<csrf/>
If you enable CSRF in the security, your post requests need to be updated to include some extra information. It explains why GET works, but POST doesn't.
In your case, try removing it, and see if it fixes the problem.
for declaring URLs which are "open" there is a typo in your XML, permitAll is given as
<security:intercept-url pattern="/auth/login" access='permitAll()' />
notice the ()

How can I map my Spring URL to a JSP file in /WEB-INF/views?

I'm having trouble doing a Spring (using 3.0.5.RELEASE) mapping. I want to map the URL http://mydomain/context-path/user/registrationform.jsp to my JSP page at
/WEB-INF/views/user/registrationform.jsp
but I'm getting a 404. I have my controller setup like so …
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
here is my dispatcher-servlet.xml …
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.burrobuie.eventmaven" />
<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>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/messages" />
</bean>
</beans>
and here is my web.xml …
<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>
What else do I need to configure (or configure differently) to make this mapping work? This is harder than - Dave
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
The RequestMapping annotation at class level should be use for a common url pattern like "item/*" and all the links that contains "/item" followed by other pattern would be mapped it to the controller. "user/" in your case
The RequestMapping annotation at method level is used for mapping the sub URL like "item/add" or "item/delete", "registrationform.jsp' in your case
So try this:
#Controller
#RequestMapping("/user")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(value="/registrationform.jsp",method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
This will map /user/registrationform.jsp
Change the RequestMapping to:
#RequestMapping("/user/registrationform.jsp")

Categories