Spring - cannot GET resources (405 error) - java

Hi i have simple Spring app:
WebConfig.java:
package spittr.web;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
registerForm.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%# page session="false" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>registration</h1>
<sf:form method="POST" commandName="spitter" >
<sf:errors path="*" element="div" cssClass="errors" />
<sf:label path="firstName"
cssErrorClass="error">name</sf:label>:
<sf:input path="firstName" cssErrorClass="error" /><br/>
....
<input type="submit" value="register" />
</sf:form>
</body>
</html>
and when i GET above register form with:
#RequestMapping(value="/register", method=GET)
public String showRegistrationForm(Model model) {
model.addAttribute("spitter", new Spitter());
return "registerForm";
}
the CSS file is not loading and I get JSP page but without CSS style and with error in Tomcat console:
127.0.0.1 - - [22/Nov/2016:18:04:48 +0100] "GET /Spittr-0.0.1-SNAPSHOT/resources/style.css HTTP/1.1" 405 1045
Where is the problem? The CSS file is in the path /Spittr-0.0.1-SNAPSHOT/resources/style.css and i specified default resource handler, so why JSP page cannot get this static file.
Thanks for any advices:)

ok i got this:
1- overriding resourceHandlerMapping() from WebMvcConfigurationSupport
#Override
#Bean
public HandlerMapping resourceHandlerMapping() {
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) super.resourceHandlerMapping();
handlerMapping.setOrder(-1);
return handlerMapping;
}
2 - overriding addResourceHandlers() from WebMvcConfigurationSupport / WebMvcConfigurerAdapter :
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

Related

Successful login with Custom login page in spring boot starter security not getting to next page

I have been studying spring boot. When using spring-boot-starter-security for a todo application,I tried to login with custom user id and password and custom login page.When I tried login , it is not taking me to next page. Note : user name is required parameter for next page.
I tried using below but after login it again takes me to login page as error
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/", "/*Todo*/**").access("hasRole('USER')").and()
.formLogin().loginPage("/login").permitAll();
}
This is my securityConfig code
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/listTodo").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll().and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Sudhakar").password("qwe123").roles("USER","ADMIN");
}
}
I would need to login with user name and get the todo details of the user who logged in. But I am not able to get to next page, after trying many times I am getting below error
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Below is my controller
package com.example.SpringLogin.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.SessionAttributes;
import com.example.SpringLogin.service.loginService;
#Controller
#SessionAttributes("name")
public class LoginController {
#Autowired
loginService service;
#RequestMapping(value="/login",method = RequestMethod.POST)
public String loginMessage(ModelMap model,#RequestParam String name,#RequestParam String password) {
boolean isValidUser=service.validateUser(name, password);
if(!isValidUser) {
model.put("message", "Invalid Credentials");
return"Room";
}
model.put("name", name);
model.put("password",password);
return "redirect:/todoList";
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String roomLogin(ModelMap model, String error) {
//model.put("name", name);
if(error!=null) {
model.addAttribute("errorMsg","UserName or Password is invalid");
}
return "Room";
}
/*#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLogin(ModelMap model) {
//model.put("name", name);
return "Welcome";
}*/
#RequestMapping(value = "/welcome")
public String showWelcome(ModelMap model) {
return "login";
}
}
My login page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<font color="red">${message}</font>
<form:form method="post" action="/login">
<fieldset class="form-group">
Name : <input type="text" name="username" class="form-control" placeholder="Username"
autofocus="true"/>
Password: <input type="password" name="password"
class="form-control" placeholder="Password" />
</fieldset>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
After successful login it should go to below page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<H1>Name : ${pageContext.request.userPrincipal.name}</H1>
<thead>
<tr>
<th>Id</th>
<th>Course</th>
<th>End Date</th>
<th>Is it Done</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${todo}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.course}</td>
<td><fmt:formatDate value="${item.date}" pattern="MM/dd/yyyy" /></td>
<td>${item.isdone?'Yes':'No'}</td>
<td><a type="button" class="btn btn-success"
href="/update-Todo?id=${item.id}">Update</a></td>
<td><a type="button" class="btn btn-warning"
href="/delete-Todo?id=${item.id}">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<a type="button" href="/add-Todo" class="btn btn-success">Add a
Todo</a>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Service class
package com.example.SpringLogin.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.SpringLogin.model.todoList;
#Service
public class TodoService {
public static List<todoList> todos=new ArrayList<todoList>();
public static int todoCount=5;
static {
todos.add(new todoList(1, "Sudhakar", "Study history", new Date(), false));
todos.add(new todoList(2,"Sudhakar","Study geography",new Date(),false));
todos.add(new todoList(3,"Sudhakar","Study GK",new Date(),false));
todos.add(new todoList(4,"Mani","Study Java",new Date(),false));
todos.add(new todoList(5,"Mani","Study script",new Date(),false));
}
public List<todoList> retrievetodos(String name){
List<todoList> retrieved=new ArrayList<todoList>();
for (todoList todo : todos) {
if(todo.getName().equalsIgnoreCase(name)) {
retrieved.add(todo);
}
}
return retrieved;
}
public void addTodo(String name,String Course,Date date,boolean isDone) {
todos.add(new todoList(++todoCount,name,Course,date,isDone));
}
public todoList retrieveTodo(int id){
for (todoList todo : todos) {
if(todo.getId()==id) {
return todo;
}
}
return null;
}
public List<todoList> UpdateTodo(todoList todo){
/*for (todoList td : todos) {
if(td.getId()==todo.getId()) {
td.setCourse(todo.getCourse());
td.setDate(todo.getDate());
}
}*/
todos.remove(todo);
todos.add(todo);
return todos;
}
//it will delete the todo
public void deleteTodo(int id) {
Iterator<todoList> it = todos.iterator();
while(it.hasNext()){
todoList td=it.next();
if(td.getId()==id) {
it.remove();
}
}
}
}
my expectation is to login application using user name and get the todolist of the user
Try adding a loginProcessUrl and a defaultSuccessUrl. Something like this:
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do_login")
.defaultSuccessUrl("/index")
index in this example is the page you want to be taken to upon successful login.
Use this one
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)

How to connect html file in resources folder with Spring Boot?

My SpringWebConfiguration.class is here:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private static Logger logger = LoggerFactory.getLogger(SpringSecurityConfig.class);
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("-----configure(HttpSecurity http)");
http.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/login")//
.defaultSuccessUrl("/userAccountInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
.defaultSuccessUrl("/")
.permitAll().
and().rememberMe().rememberMeParameter("remember-me").key("uniqueAndSecret").tokenValiditySeconds(1296000).userDetailsService(userDetailsService)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.deleteCookies("guid")
.deleteCookies("JSESSIONID")
.permitAll()
.and().csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
logger.info("-----configureGlobal(AuthenticationManagerBuilder auth)");
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
}
My LoginController:
#RestController
public class LoginController() {
#GetMapping("/login")
public String login(Model model) {
return "/login";
}
}
My html file:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Stacked form</h2>
<form th:action="#{/login}" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember"> Remember me
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
When I open browser and go to "localhost:8080/login". It returns String "/login", not html login page. Why? Maybe I missed something to connect to my html file. I think my controller need something like an url to connect to html file. I don't understand how it work correctly. Help me please!
First, you need to modify LoginController
#Controller
public class LoginController() {
#GetMapping("/login")
public String login(Model model) {
return "/login";
}
}
If it does not work then convert html to jsp page.
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Add ViewResolver to your configuration class along with your code.
You need to add a view resolver to your spring configurations.
This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL
Example:
#EnableWebMvc
#Configuration
#ComponentScan("com.baeldung.web")
public class WebConfig implements WebMvcConfigurer {
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
For such simplicity of the example, we don't need a controller to process the request.
We only need a simple jsp page, placed in the /WEB-INF/view folder as defined in the configuration.
Source:
https://www.baeldung.com/spring-mvc-view-resolver-tutorial

Unable to logout using spring 4 MVC

I have used spring 4 MVC in my project which is annotation based.
I am able to login successfully but I am not able to logout.
I have posted the configuration,initializer and controller classes below
along with the login page and welcome page.Please let me know what changes need to be done to my code so that I log out successfully.
I am currently getting the below error on logout
Feb 06, 2017 2:36:03 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/Student_Login/%3Cc:url%20value='/login'%20/%3E] in DispatcherServlet with name 'dispatcher'
AppConfig_login
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.student.login")
public class AppConfig_login {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("message");
return messageSource;
}
}
AppInitializer_login
public class AppInitializer_login extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig_login.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}}
AppController
package com.student.login.controller;
import java.util.List;
import java.util.Locale;
#Controller
#RequestMapping("/")
public class AppController_login {
#Autowired
StudentService service;
#Autowired
MessageSource messageSource;
/*
* This method will list all existing employees.
*/
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String listStudents(ModelMap model) {
//List<Student> students = service.findAllStudents();
//model.addAttribute("students", students);
Student student = new Student();
model.addAttribute("student", student);
return "login";
}
#RequestMapping(value = { "/" }, method = RequestMethod.POST)
public String checkCredentials(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "login";
}
System.out.println(student.getRoll_no());
System.out.println(student.getPassword());
/*
* Preferred way to achieve uniqueness of field [ssn] should be implementing custom #Unique annotation
* and applying it on field [ssn] of Model class [Employee].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(service.isCredentialValid(student.getRoll_no(),student.getPassword())){
FieldError login_Error =new FieldError("student","password",messageSource.getMessage("non.unique.credentials", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(login_Error);
return "login";
}
//service.saveStudent(student);
model.addAttribute("welcome", "Welcome Student " + student.getName() + " registered successfully");
return "welcome_student";
}
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String logoutPage(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
//model.addAttribute("edit", false);
return "login";
}
/*
* This method will provide the medium to add a new employee.
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.GET)
public String newStudent(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("edit", false);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* saving employee in database. It also validates the user input
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if(!service.isStudentRollNoUnique(student.getRoll_no())){
FieldError roll_no_Error =new FieldError("student","roll_no",messageSource.getMessage("non.unique.roll_no", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(roll_no_Error);
return "registration";
}
service.saveStudent(student);
model.addAttribute("success", "Student " + student.getName() + " registered successfully");
return "login_success";
}}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Login Form</h2>
<form:form method="POST" modelAttribute="student">
<!-- <form:input type="hidden" path="id" id="id"/>-->
<table>
<tr>
<td><label for="roll_no">Roll No:</label> </td>
<td><form:input path="roll_no" id="roll_no"/></td>
<td><form:errors path="roll_no" cssClass="error"/></td>
</tr>
<tr>
<td><label for="password">Password:</label> </td>
<td><form:input path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to Registration
</body>
</html>
welcome_student
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hello user
Logout
</body>
</html>
So I finally figured out that the problem was in my jsp welcome_student
I forgot to include the below line
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Spring MVC, JSP do nor load properly my css

I created simple web-app using spring mvc with form in jsp and some css in it. I run it on tomcat7
Thats my code:
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.springinaction.spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
#Controller
#RequestMapping(value = "/spitter")
public class SpitterController {
#Autowired
public SpitterController(SpitterRepository spitterRepository){
this.spitterRepository = spitterRepository;
}
public SpitterController() {}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm(Model model) {
model.addAttribute(new Spitter());
return "registrationForm";
}
}
Finally jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Spittr</title>
<style>
div.errors {
backgraund-color: #ffcccc;
border: 2px solid red;
}
label.error {
color: #ffcccc;
}
input.error{
backgraund-color: #ffcccc;
}
</style>
</head>
<br>
<h1>Rejestracja</h1>
<sf:form method="POST" commandName="spitter">
<sf:errors path="*" cssClass="errors" element="div"/>
<sf:label path="firstName" cssErrorClass="error">Imię:</sf:label>
<sf:input path="firstName"/><br/>
<sf:label path="lastName" cssErrorClass="error">Nazwisko:</sf:label>
<sf:input path="lastName"/><br/>
<sf:label path="username" cssErrorClass="error">Nazwa użytkownika: </sf:label>
<sf:input path="username"/><br/>
<sf:label path="email" cssErrorClass="error">Email:</sf:label>
<sf:input path="email" type="email"/><br/>
<sf:label path="password" cssErrorClass="error">Password:</sf:label>
<sf:password element="span" path="password"/><br/>
<input type="submit" value="Zarejestruj"/>
</sf:form>
<hr />
</body>
</html>
My problem is that, when i'am opening website under my browser(doesn't matter which one) just part of css's is loaded. It uses only border: 2px solid red; and color: #ffcccc;. I can't find solution for that problem. Could it be some issue with encoding? I have the same problem when I import css from outside. I even used bootstrap css. Funny thing is that css's worked for some time and unexpectedly stopped.
Any ideas?

simple AJAX JQuery example gives me 500 internal server error

hi i'm working in a spring mvc project and i'm getting this error when i hit the button in my form
500 (Internal Server Error) jquery.min.js:6
x.ajaxTransport.x.support.cors.e.crossDomain.send jquery.min.js:6
x.extend.ajax AddUser:19
doAjaxPost AddUser:41
onclick
i'm trying to do a simple AJAX JQuery example that adds users to a list but i get that error when i press the add button in my form
this is my controller class:
#Controller
public class UserListController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value="AddUser",method=RequestMethod.GET)
public String showForm(){
return "AddUser";
}
#RequestMapping(value="AddUser",method=RequestMethod.POST)
public #ResponseBody String addUser(#ModelAttribute(value="user") User user, BindingResult result )
{
String returnText;
if(!result.hasErrors())
{
userList.add(user);
returnText = "User has been added to the list. Total number of users are " + userList.size();
}
else
{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value="ShowUsers")
public String showUsers(ModelMap model)
{
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
and this is my AddUser.jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users using ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!-- <script src="resources/js/libs/jquery-2.0.2.min.js"></script> -->
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUser",
data: "name=" + name + "&education=" + education,
success: function(response){
// we have the response
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<table>
<tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
<tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
<tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
</table>
Show All Users
</body>
</html>
and my MvcConfiguration class since i'm using a java based configuration and not using XML
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "controllers" })
public class MvcConfig extends WebMvcConfigurerAdapter
{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// JSP VIEW-RESOLVER
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setOrder(2);
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
return bean;
}
}
EDIT: i starter a new project just for the sake of trying to know what error i'm having, i delete spring secuirty in my application, but i still can figure out whats wrong.
1) i actually dont delete spring security i just starte a new project to try to solve my url problem
2) i change my controllers and the URL attribute in my ajax script
new RequestMapping controllers:
#RequestMapping(value="AddUser",method=RequestMethod.GET)
i deleted the "/" in the value="AddUser"
i dont have a "/" in any of my controllers if put a "/" in the controllers i have the same 500 Internal server error
This might be because of the CSRF protection which is enabled by default in Java configuration. Try in your configuration...
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.csrf().disable();
}
Let me know if this works.
EDIT**
To include CSRF token in AJAX request, if you are using JSON, you need to put it on the http header. Sample JSP example typically would be...
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>
Then in your javascript call, get this parameters and add it to XMLHttpRequest's header.
Hope this helps.
Further reading
In my case, i had to add the below dependency to my pom
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency>

Categories

Resources