I'm developing a Java application and I'm using Spring MVC. I'm a newbie and I'm trying to load some static content like css files and images in my home page. When I try to load some of these files I get a 405 error (GET method not allowed).
My project structure (for the web part) is
-WebContent
--MetaInf
--resources
--views
--WEB_INF
---web.xml
---springapp-dispatcher.xml
here's 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"
metadata-complete="true">
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my springapp-dispatcher.xml (without the initial part)
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**"
location="/resources/" />
<context:component-scan base-package="polibeacon.web"></context:component-scan>
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
I only have a controller, named HomeController.java
#Controller
public class HomeController {
#RequestMapping( value = "/", method = RequestMethod.GET )
public String index(Model model) {
model.addAttribute(new User());
return "index";
}
#RequestMapping(value="/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute(new User());
return "registration";
}
#RequestMapping(method=RequestMethod.POST)
public String registerUser(#Valid User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "registration";
}
// save user
return "index";
}
}
and here's the index.jsp page
<!-- CSS -->
<link href="<c:url value="/resources/bootstrap/css/bootstrap.min.css" />" rel = "stylesheet">
<link href="<c:url value="/resources/css/style.css" />" rel = "stylesheet">
<!-- Scripts -->
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-3"></div>
<div class = "col-md-6">
<div class = "jumbotron" style = "text-align: center;">
<img src = "images/logo.png" style = "display: block; margin-left: auto; margin-right: auto;">
<h2>Header</h2>
<form:form method="post" modelAttribute="user">
<form:input path="username" placeholder="Username"/>
<form:password path="password" placeholder="Password"/>
</form:form>
</div>
</div>
</div>
Sign Up
</div>
</body>
</html>
what's wrong?
Related
I have simple controller which must save my form in DB. I tried mapping command "/tests/review/saveChanges" in this controller but when I push button "save" I have "HTTP Status 400 – Bad Request".
My controller:
#Controller
#RequestMapping(value = "/tests")
public class TestController {
private TestInterfaceService testService;
#Autowired(required = true)
#Qualifier(value = "testService")
public void setTestService(TestInterfaceService testService) {
this.testService = testService;
}
//here we get list objects
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String listTests(Model model) {
model.addAttribute("test", new Test());
model.addAttribute("listTests", this.testService.listTests());
return "proposals";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addTest(Test t) {
if (t.getId() == 0) {
this.testService.addTest(t);
} else {
// existing person, call update
this.testService.updateTest(t);
}
return "redirect:/tests/list";
}
#RequestMapping(value = "/remove/{id}")
public String removeTest(#PathVariable("id") long id) {
this.testService.removeTest(id);
return "redirect:/tests/list";
}
//Here we start work with specific object
#RequestMapping("/review/{id}")
public String editTest(#PathVariable("id") long id, Model model) {
Test test = this.testService.getFullTestById(id);
model.addAttribute("candidateTest", test);
model.addAttribute("candidateQuestions", test.getQuestions());
model.addAttribute("candidateAnswers", test.getQuestions());
return "review";
}
//Here I'm try save all changes
#ModelAttribute("candidateTest")
#RequestMapping(value = "/review/saveChanges", method = RequestMethod.POST)
public String review(#PathVariable("candidateTest") Test candidateTest, Model model) {
testService.addTest(candidateTest);
return "redirect:/tests/list";
}
#RequestMapping(value = "/choise/{id}/{status}", method = RequestMethod.GET)
public String choise(#PathVariable("id") long id, #PathVariable("status") String status, Model model) {
Test test = this.testService.getTestById(id);
test.setStatus(TestStatus.Developing.getStatus(status));
this.testService.updateTest(test);
model.addAttribute("test", this.testService.getTestById(id));
model.addAttribute("questions", this.testService.getListQuestionsById(id));
return editTest(id, model);
}
#RequestMapping(value = "/previewTest/{id}")
public String previewTest(#PathVariable("id") long id, Model model) {
Test test = this.testService.getTestById(id);
model.addAttribute("ourTest", test);
return "previewTest";
}
}
My jsp review:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page session="true"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="${contextPath}/resources/css/bootstrap.min.css">
<script src="${contextPath}/resources/js/jquery-3.2.1.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="left">
<c:url var="formTestUrl" value="/tests/list" />
<spring:message code="back.to.proposals" />
</h1>
<span style="float: right">ru | ua | en </span>
<br>
//And here we have something whorg I'm guest.
<form:form modelAttribute="candidateTest"
action="/tests/review/saveChanges" method="POST">
<table>
<tr>
<td><spring:message code="test.name" /></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><spring:message code="test.free" /></td>
<td><form:input path="free" /></td>
</tr>
<c:forEach items="${candidateTest.questions}" var="question"
varStatus="status">
<tr>
<td align="center">${status.count}</td>
<td><input name="questions[${status.index}].text"
value="${question.text}" /></td>
</tr>
<c:forEach items="${question.answers}" var="answer"
varStatus="interator">
<td align="center">${interator.count}</td>
<td><input name="answers[${interator.index}].answer"
value="${answer.answer}" /></td>
</c:forEach>
</c:forEach>
</table>
<br />
<input type="submit" value="Save" />
</form:form>
<div class="container">
<div class="btn-group">
<button type="button" class="btn btn-primary">
<spring:message code="choise" />
</button>
<button type="button" class="btn btn-primary dropdown-toggle"
data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"app"}' />"><spring:message
code="aprove" /></a></li>
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"pro"}' />"><spring:message
code="return" /></a></li>
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"dis"}' />"><spring:message
code="refuse" /></a></li>
</ul>
</div>
</div>
</body>
</html>
When we start review one test we have specific link "http://localhost:8089/Diplom/tests/review/1", then when we push save-button we have this link "http://localhost:8089/tests/review/saveChanges" , "Diplom" it is our contextPath which lost. Of course we can change in jsp link like ${contextPath}/tests/review/saveChanges and I did it. And it didn't help.
========
UPD
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"
version="3.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>CharsetFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
spring mvc config xml:
e<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<!--<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"> <list> <value>classpath:validation</value> </list>
</property> </bean> -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/locales/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Though it was asked a long time ago...
Instead of
${contextPath}/tests/review/saveChanges
Try
${pageContext.request.contextPath}/tests/review/saveChanges
Let me know if it worked!
I have a pretty nasty and frustrating problem with a Maven Web Application, holding me back for some time.
Apparently, from my previous google searches, this is a common Spring MVC error, but i am not able to find the solution i need among the ones offered on the internet so far. Note that i am a beginner in Spring and in MVC concepts in general.
I have a web application which is supposed to manage a building administration (inhabitants, rent calculations, etc). I use Spring MVC, Hibernate, Java 1.8, Tomcat 8 server container, and SQL Server 2014.
Firstly, this is my POJO for the bulding residents, a type called Inhabitant:
#Entity
#Table (name = "INHABITANT")
public class Inhabitant {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "ID")
private long id;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Column(name = "APARTAMENT_NUMBER")
private String apartamentNumber;
#Column(name = "APARTAMENT_OWNER")
private String apartamentOwner;
#Column(name = "TELEPHONE_NUMBER")
private String telephoneNumber;
#Column(name = "EMAIL_ADDRESS")
private String emailAddress;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getApartamentNumber() {
return apartamentNumber;
}
public void setApartamentNumber(String apartamentNumber) {
this.apartamentNumber = apartamentNumber;
}
public String getApartamentOwner() {
return apartamentOwner;
}
public void setApartamentOwner(String apartamentOwner) {
this.apartamentOwner = apartamentOwner;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
public void setTelephoneNumber(String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
This is my dispatcher-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"
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.xsd">
<context:component-scan base-package="laura.bachelordegree.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <!-- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" -->
<display-name>BuildingAdministration</display-name>
<welcome-file-list>
<welcome-file>login/index.jsp</welcome-file>
</welcome-file-list>
<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>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>/login</url-pattern>
</servlet-mapping>
</web-app>
This is my jsp registration form, which should map to the Inhabitant object:
<!DOCTYPE html>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%#page session="false" %>
<html>
<head>
<meta charset="utf-8" />
<title>Registration</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="login/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="login/font-awesome/css/font-awesome.min.css" />
<script type="text/javascript" src="login/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="login/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Registration form - START -->
<div class="container">
<div class="row">
<%-- <form role="form"> --%>
<form:form method="post" modelAttribute="inhabitant" role="form" action="BuildingAdministration/src/main/webapp/login/result">
<div class="col-lg-6">
<div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>
<div class="form-group">
<label for="InputFirstName">Enter First Name</label>
<div class="input-group">
<form:input path="firstName" type="text" cssClass="form-control" id="InputFirstName" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputLastName">Enter Last Name</label>
<div class="input-group">
<form:input path="lastName" type="text" cssClass="form-control" id="InputLastName" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputApartmentNumber">Enter Apartment Number</label>
<div class="input-group">
<form:input path="apartmentNumber" type="text" cssClass="form-control" id="InputApartmentNumber" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputApartmentOwner">Enter Apartment Owner</label>
<div class="input-group">
<form:input path="apartmentOwner" type="text" cssClass="form-control" id="InputApartmentOwner" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputTelephoneNumber">Enter Telephone Number</label>
<div class="input-group">
<form:input path="telephoneNumber" type="text" cssClass="form-control" id="InputTelephoneNumber" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputEmail">Enter Email</label>
<div class="input-group">
<form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailFirst" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputEmail">Confirm Email</label>
<div class="input-group">
<form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailSecond" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
</div>
</form:form>
<%-- </form> --%>
<div class="col-lg-5 col-md-push-1">
<div class="col-md-12">
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-ok"></span> Success! Message sent.</strong>
</div>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-remove"></span><strong> Error! Please check all page inputs.</strong>
</div>
</div>
</div>
</div>
</div>
<!-- Registration form - END -->
</body>
</html>
And finally, the controller class, which should effectively map the data from the jsp form with the java entity, Inhabitant:
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String loadInhabitant(#ModelAttribute("inhabitant")Inhabitant inhabitant,
ModelMap model) {
model.addAttribute("firstName", inhabitant.getFirstName());
model.addAttribute("lastName", inhabitant.getLastName());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
model.addAttribute("emailAddress", inhabitant.getEmailAddress());
return "result";
}
Now, this is the error i get whenever i try to run my application on the server:
message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'inhabitant' available as request attribute
description The server encountered an internal error that prevented it from fulfilling this request.
exception org.apache.jasper.JasperException:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'inhabitant' available as request
attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:471)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause java.lang.IllegalStateException: Neither BindingResult nor
plain target object for bean name 'inhabitant' available as request
attribute
org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.login.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:322)
org.apache.jsp.login.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:216)
org.apache.jsp.login.index_jsp._jspService(index_jsp.java:148)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I have tried a thousand things, but i just can't get it to work. So, please, can someone point out what i'm doing wrong? How can i correctly build the java object based on the information from the jsp form?
Thanks in advance!
It seems you need to understand more about spring mvc.
You are mapping your form request to a view. you must map your form request to a controller method not a view, your form should look like this :
<form:form action="${pageContext.request.contextPath}/inhabitant/create" method="post" modelAttribute="inhabitant" >
....
// have a look at spring form validation
// have a look at spring form elements eg. how error messages are displayed
</form:form>
You need two methods in controller to create and save inhabitant one for showing a form and another for saving form datas into database. Now your controller should look like this :
#Controller
#RequestMapping(value="/inhabitant")
public class PostController {
#Autowired
private InhabitantService inhabitantService;
//Method that displays the form page
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String createForm(Model model ) {
model.addAttribute("inhabitant", new Inhabitant()); // identifier should be same as modelattribute in your form "inhabitant"
return "formpage"; // your form page name
}
// Method which will have the submitted data
// Validation is also done in this method
#RequestMapping(value="/create", method=RequestMethod.POST)
public String saveForm( #ModelAttribute("inhabitant") #Valid Inhabitant inhabitant, //#valid is used for validation use it If you are doing validation
BindingResult result // use only if you are doing validation)
{
// use only If you are doing validation
// If validation fails users must return to the same form view
if (result.hasErrors()){
return "formpage";
}
//and save the submitted form data
inahabitantService.saveInhabitant(inhabitant);
enter code here
return "success"; // success.jsp is a success page that you will see after creating a inhabitant
}
Do not use '/login' as a url patern in your web.xml Just dont do it.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/login</url-pattern> //Just Use '/' instead of '/login'
</servlet-mapping>
I doubt that you have configured hibernate properly Post your hibernateConfiguration.xml file and persistence.xml file.
You must learn and understand these: Just take your time.
Spring Model Controller View and how does it really work
Spring Form elements, Spring Form Validation
Jpa / hibernate basics / association in hibernate
Jsp taglibs / JSP inside Jsp / Apache Tiles
Don't do that
model.addAttribute("firstName", inhabitant.getFirstName());
model.addAttribute("lastName", inhabitant.getLastName());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
model.addAttribute("emailAddress", inhabitant.getEmailAddress());
Do this instead
model.addAttribute("inhabitant", inhabitant);
Hei guys! I have a servlet config as below.
vietjob-servlet
<mvc:annotation-driven />
<context:component-scan base-package="vjb.de.vietjob" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/" view-name="index" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:lang" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
And in web xml i declare the uri for servlet
web.xml
<servlet>
<servlet-name>vietjob</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>vietjob</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
If i write all controller request mapping under /, everything is ok, servlet can load all libraries inside resources folder. But when i give controller a segment, i got error with
WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI
For details the link localhost:8001/vjb.de/ehdokas.do is working but localhost:8001/vjb.de/employee/ehdokas.do not work. I guess that when i give a segment, the servlet will scan employee/resources instead /resources, so the error occurred.
And another issue: when user login into system, the link was changed from http://localhost:8001/vjb.de/ehdokas.do to http://localhost:8001/vjb.de/employee/ehdokas.do. How can i config a same controller with all urls, i mean controller can run without relative to url address. Every link abc/def/ehdokas.do or abc/ehdokas.do also call to controller ehdokas.do?!
Controller class
#Controller
#RequestMapping(value = "/employee")
public class EhdokasController {
#Inject
private EhdokasDao ehdokasdao;
#Inject
private AlaDao aladao;
public AlaDao getAlaDao(){
return aladao;
}
public void setAlaDao(AlaDao aladao){
this.aladao=aladao;
}
public EhdokasDao getEhdokasDao() {
return ehdokasdao;
}
public void setEhdokasDao(EhdokasDao ehdokasdao) {
this.ehdokasdao = ehdokasdao;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String showEmployeePage(#RequestParam(value="tunnus") String tunnus, Model model){
System.out.println("ehdokasdao: "+ehdokasdao);
EhdokasImpl ehdokas = (EhdokasImpl) ehdokasdao.getEhdokasByTunnus(tunnus);
model.addAttribute("ehdokas", ehdokas);
return "ehdokas/ehdokas_home";
}
// Siirtää ehdokas lomake sivulle
#RequestMapping(value = "/lomake.do", method = RequestMethod.GET)
public String forwardToLomake(Model model) {
Ehdokas ehdokas = new EhdokasImpl();
List<Integer> listId = aladao.getListAlaId();
model.addAttribute("listId", listId);
model.addAttribute("ehdokas", ehdokas);
return "lomake/lomake_ehdokas";
}
// ota syötetyt tiedot lomakkeesta
#RequestMapping(value = "/lomake.do", method = RequestMethod.POST)
public String getTietoLomake(
#ModelAttribute(value = "ehdokas") #Valid EhdokasImpl ehdokas, BindingResult result, Model model) {
if (result.hasErrors()) {
return "lomake/lomake_ehdokas";
} else {
ehdokasdao.postEhdokas(ehdokas);
return "redirect:/ehdokas.do";
}
}
// näytä kaikki ehdokkaat tietokannasta
#RequestMapping(value = "/ehdokas.do", method = RequestMethod.GET)
public String showEhdokkaat(Model model) {
List<String> kaupunkiList = ehdokasdao.getKotiKaupunki();
List<Ehdokas> ehdokkaat = ehdokasdao.showEhdokas();
model.addAttribute("ehdokkaat", ehdokkaat);
model.addAttribute("kaupunkiList", kaupunkiList);
model.addAttribute("ehdokas", new EhdokasImpl());
return "ehdokas/ehdokas_list";
}
#RequestMapping(value = "/ehdokas.do", method = RequestMethod.POST)
public String showEhdokkaat(
#ModelAttribute(value = "ehdokas") EhdokasImpl ehdokas,#PathVariable(value="kaupunki") String kaupunki, #PathVariable(value="id") int id,#RequestParam(value="submit") String submit, Model model) {
System.out.println(submit);
if(submit.equals("Hae") || submit.equals("Search")){
List<String> kaupunkiList = ehdokasdao.getKotiKaupunki();
List<Ehdokas> ehdokkaat = ehdokasdao.getEhdokasByKaupunki(kaupunki);
model.addAttribute("ehdokkaat", ehdokkaat);
model.addAttribute("kaupunkiList", kaupunkiList);
return "ehdokas/ehdokas_list";
} else if (submit.equals("More") || submit.equals("Lisätieto")){
model.addAttribute("id",id);
return "redirect:yksiehdokas.do";
} else
return "redirect:ehdokas.do";
}
#RequestMapping(value="/yksiehdokas.do", method=RequestMethod.GET)
public String showYksiEhdokas(#RequestParam(value="id") int id, Model model ){
Ehdokas ehdokas = ehdokasdao.searchEhdokasById(id);
model.addAttribute("ehdokas", ehdokas);
return "ehdokas/ehdokas_yksi";
}
/*siirrä apply sivulle*/
#RequestMapping(value="/apply.do", method= RequestMethod.GET)
public String forwardToApply(Model model){
Kayttaja kayttaja = new KayttajaImpl();
Ehdokas ehdokas = new EhdokasImpl();
model.addAttribute("kayttaja", kayttaja);
model.addAttribute("ehdokas", ehdokas);
return "apply";
}
#RequestMapping(value="/apply.do", method= RequestMethod.POST)
public String getInfoEmployee(#ModelAttribute(value="ehdokas") EhdokasImpl ehdokas){
ehdokasdao.postEhdokas(ehdokas);
return "redirect:ehdokas.do";
}
#ModelAttribute("kieliList")
public List<String> getKieli() {
List<String> list = new ArrayList<String>();
list.add("English");
list.add("Finnish");
list.add("Germany");
return list;
}
#ModelAttribute("tutkinnot")
public List<String> getTutkinto() {
List<String> list = new ArrayList<String>();
list.add("Päiväkoti");
list.add("Peruskoulu");
list.add("Lukio");
list.add("AMK");
list.add("Yliopisto");
return list;
}
}
Jsp file
<%# page session="false"%>
<%# 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" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# 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">
<%# include file="/WEB-INF/views/templates/navbar-bootstrap.jsp"%>
<%# include file="/WEB-INF/views/templates/logo-banner.jsp"%>
<%# include file="/WEB-INF/views/templates/menu-bootstrap.jsp"%>
<script src="<c:url value="resources/bootstrap-3.3.6/js/bootstrap.min.js" />"></script>
<link href="resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="resources/js/jquery-1.12.2.min.js"></script>
<style>
/* Set black background color, white text and some padding */
.container-fluid {
width: 1000px;
margin: auto;
}
.form-control{
width: 30px;
}
</style>
<title><spring:message code="employee.page.list" /></title>
</head>
<body>
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2 sidenav">
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="col-sm-8 text-left">
<form:form class="form-inline" action="ehdokas.do" modelAttribute="ehdokas" method="POST">
<form:select class="form-control" path="kaupunki">
<form:option value="">select city</form:option>
<form:options items="${kaupunkiList}"></form:options>
</form:select>
<spring:message code="button.search" var="search" />
<input type="submit" name="submit" value="${search }" />
</form:form>
<h3><spring:message code="kaikki.ehdokas"></spring:message></h3>
<hr>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>City</th>
</tr>
</thead>
<tbody>
<c:forEach var="ehdokas" items="${ehdokkaat}">
<tr>
<td><c:out value="${ehdokas.suku} "></c:out></td>
<td><c:out value="${ehdokas.etu} "></c:out></td>
<td><c:out value="${ehdokas.sukupuoli} "></c:out></td>
<td><c:out value="${ehdokas.kaupunki} "></c:out></td>
<form:form action="ehdokas.do" method="post">
<input type="hidden" name="id" value="${ehdokas.id }" />
<spring:message code="button.more" var="more"/>
<td><input type="submit" name="submit" class="btn btn-info" value="${more }" /></td>
</form:form>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="col-sm-2 sidenav">
<div class="well">
<p>ADS</p>
</div>
<div class="well">
<p>ADS</p>
</div>
</div>
</div>
</div>
<%# include file="/WEB-INF/views/templates/footer-bootstrap.jsp"%>
</body>
</html>
I am starting to use dropzone.js and I wanted to uploaded a file and unfortunately this job doesn't work. I mention that I've been inspired from a working project.
So this is my controller class:
#Controller
public class FileUploadController {
private FileUploadService uploadService = (FileUploadService) SpringContext.CONTEXT
.getContext().getBean(FileUploadService.class);
#RequestMapping(value = { "/file" })
public String home() {
return "fileUploader";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody List<UploadedFile> upload(
MultipartHttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println("Enter in upload.....");
// Getting uploaded files from the request object
Map<String, MultipartFile> fileMap = request.getFileMap();
// Maintain a list to send back the files info. to the client side
List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();
// Iterate through the map
for (MultipartFile multipartFile : fileMap.values()) {
// Save the file to local disk
saveFileToLocalDisk(multipartFile);
UploadedFile fileInfo = getUploadedFileInfo(multipartFile);
// Save the file info to database
fileInfo = saveFileToDatabase(fileInfo);
// adding the file info to the list
uploadedFiles.add(fileInfo);
}
return uploadedFiles;
}
#RequestMapping(value = { "/list" })
public String listBooks(Map<String, Object> map) {
map.put("fileList", uploadService.listFiles());
return "/listFiles";
}
#RequestMapping(value = "/get/{fileId}", method = RequestMethod.GET)
public void getFile(HttpServletResponse response, #PathVariable int fileId) {
UploadedFile dataFile = uploadService.getFile(fileId);
File file = new File(dataFile.getLocation(), dataFile.getName());
try {
response.setContentType(dataFile.getType());
response.setHeader("Content-disposition", "attachment; filename=\""
+ dataFile.getName() + "\"");
FileCopyUtils.copy(FileUtils.readFileToByteArray(file),
response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveFileToLocalDisk(MultipartFile multipartFile)
throws IOException, FileNotFoundException {
String outputFileName = getOutputFilename(multipartFile);
FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(
outputFileName));
}
private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) {
return uploadService.saveFile(uploadedFile);
}
private String getOutputFilename(MultipartFile multipartFile) {
return getDestinationLocation() + multipartFile.getOriginalFilename();
}
private UploadedFile getUploadedFileInfo(MultipartFile multipartFile)
throws IOException {
UploadedFile fileInfo = new UploadedFile();
fileInfo.setName(multipartFile.getOriginalFilename());
fileInfo.setSize(multipartFile.getSize());
fileInfo.setType(multipartFile.getContentType());
fileInfo.setLocation(getDestinationLocation());
fileInfo.setActuality("previous");
return fileInfo;
}
private String getDestinationLocation() {
return "D:/uploaded-files/";
}
}`
In upload method I put a message (System.out.println("Enter in upload.....")) to check if entered in this method but don't enters.
The 'fileUploader' jsp is:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" name="viewport"
content="width=device-width, initial-scale=1">
<title>Spring MVC + Dropzone.js Example</title>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/libs/bootstrap-3.1.1/css/bootstrap.min.css"/>'>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/libs/bootstrap-dialog/css/bootstrap-dialog.min.css"/>'>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/css/style.css"/>'>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading text-center">
<h3>Spring MVC + Dropzone.js Example</h3>
</div>
<div class="panel-body">
<div>
<form id="dropzone-form" class="dropzone"
enctype="multipart/form-data">
<div
class="dz-default dz-message file-dropzone text-center well col-sm-12">
<span class="glyphicon glyphicon-paperclip"></span> <span>
To attach files, drag and drop here</span><br> <span>OR</span><br>
<span>Just Click</span>
</div>
<!-- this is were the previews should be shown. -->
<div class="dropzone-previews"></div>
</form>
<hr>
<button id="upload-button" class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<a class="btn btn-primary pull-right" href="list">
<span class="glyphicon glyphicon-eye-open"></span> View All Uploads
</a>
</div>
</div>
</div>
</div>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/jquery/jquery-2.1.1.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/bootstrap-3.1.1/js/bootstrap.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/bootstrap-dialog/js/bootstrap-dialog.min.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/dropzone.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/js/app.js"/>'></script>
</body>
</html>`
Now the problem is an error that appears when I press the 'upload' button after I selected a file.The error is :
<html><head><title>Apache Tomcat/7.0.57 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 405 - Request method 'POST' not supported</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Request method 'POST' not supported</u></p><p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.57</h3></body></html>
Above error appears in browser, in console doesn't appear anything.
My servlet cod is the following:
<?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 http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- 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/" />
<!-- Handles HTTP GET requests for /web-resources/** by efficiently serving
up static resources in the ${webappRoot}/resources/ directory -->
<!-- Defines a resolver implementation bean. It gets applied to all requests
handled by that DispatcherServlet -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<beans:property name="useTrailingSlashMatch" value="true" />
</beans:bean>
<resources mapping="/web-resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean id="viewResolver"
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.license.web.*" />
</beans:beans>
Thanks a lot in advance!
I am trying to make a very simple flow using Spring, jQuery, Ajax and Json. But I am not able to send a POST request to Spring controller. Also my eclipse shows compilation error when I am trying to use consumes and produces in #RequestMapping. I am not using maven. It is a simple dynamic web project in eclipse. I am using spring 3.0.5 jars.
HTML page.
<html>
<head>
<style>
div {
border: 1px solid #000000;
}
</style>
<script src="/JSONProject/js/jquery-1.11.0.min.js"></script>
<script>
var user="";
var pwd1="";
var json="";
var strJson="";
$(document).ready(function(){
$("#button").click(function(){
console.log("inside click");
user=$("#userName").val();
pwd1=$("#password").val();
json={username:user,password:pwd1};
console.log("json: "+json);
strJson=JSON.stringify(json);
console.log("strJson: "+strJson);
$.ajax({
type: "POST",
url: "http://localhost:8080/JSONProject/add.html",
contentType: 'application/json',
data: JSON.stringify(json)
})
.done(function(resultUserDTO) {
JSON.stringify(resultUserDTO)
alert("result: "+resultUserDTO);
});
});
});
</script>
</head>
<body>
<FORM>
Please enter your text:
<BR>
<div >
<label id="uName">Username</label>
<input id="userName"/>
<br>
<label id="pwd">Password</label>
<input id="password" type="Password" id="pwd"/>
</div>
<BR>
<INPUT id="button" TYPE="SUBMIT" VALUE="Submit">
</FORM>
</body>
</html>
Controller:
package demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import demo.model.Login;
#Controller
public class HelloWorldController {
Login users;
#RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.0!";
System.out.println("Inside controller");
return new ModelAndView("hello", "message", message);
}
/**
* Handles POST request
*/
#RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json")
public String processJson(#RequestBody String requestBody){
return "Handled application/json request ";
}
}
I am getting the following compilation error:
The attribute consumes is undefined for the annotation type RequestMapping
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
spring-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"
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="demo.controller" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".htm" />
</bean>
</beans>
index.jsp
<html>
<head>
<title>Spring with ajax</title>
</head>
<body>
Say Hello
</body>
</html>
When I click the hello.html link in index.jsp, hello.html opens and i get the syso of the controller method that handles "\hello" and get. But when i make a POST request using jquery, i still see the syso of the method that handle "\hello" and get method on console..
Really confused.
Please help
Thank you in advance!!
New updated code after the suggestions given. Code has complied. Yet not call to POST handler. Syso inside POST handler is not getting printed on eclipse console.
Controller:
package demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import demo.model.Login;
#Controller
public class HelloWorldController {
Login users;
#RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.0!";
System.out.println("Inside controller");
return new ModelAndView("hello", "message", message);
}
/**
* Handles request for adding two numbers
*/
#RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json",produces = "application/json")
public #ResponseBody String processJson(#RequestBody String requestBody){
System.out.println("inside controller 2");
return "Handled application/json request ";
}
}
hello.html:
<html>
<head>
<style>
div {
border: 1px solid #000000;
}
</style>
<script src="/JSONProject/js/jquery-1.11.0.min.js"></script>
<script>
var user="";
var pwd1="";
var json="";
var strJson="";
$(document).ready(function(){
$("#button").click(function(){
console.log("inside click");
user=$("#userName").val();
pwd1=$("#password").val();
json={username:user,password:pwd1};
console.log("json: "+json);
strJson=JSON.stringify(json);
console.log("strJson: "+strJson);
$.ajax({
type: "POST",
url: "http://localhost:8080/JSONProject/add.html",
contentType: 'application/json',
data: JSON.stringify(json)
})
.done(function(resultUserDTO) {
JSON.stringify(resultUserDTO)
alert("result: "+resultUserDTO);
});
});
});
</script>
</head>
<body>
<FORM method="post">
Please enter your text:
<BR>
<div >
<label id="uName">Username</label>
<input id="userName"/>
<br>
<label id="pwd">Password</label>
<input id="password" type="Password" id="pwd"/>
</div>
<BR>
<INPUT id="button" TYPE="SUBMIT" VALUE="Submit">
</FORM>
</body>
</html>
P.S: I have used 3.2.0 version
The produces and consumes attributes have been introduced with spring 3.1. See: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.1.html
You are using spring 3.0.x, so your program won't compile and therefore won't do anything.
Also, as configured, your add method's return value will be used as a view name ( A view with name "Handled application/json request "). If you want to handle the content generation by yourself annotate your add method with #ResponseBody.
Also your js handler is calling the wrong url:
$.ajax({
url: "http://localhost:8080/JSONProject/add.html"
});
vs.
#RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json")
public String processJson(#RequestBody String requestBody){
Either change the js/ajax url to http://localhost:8080/JSONProject/add or your request mapping to #RequestMapping(value = "/add.html",method = RequestMethod.POST ,consumes = "application/json")
Following is my observation, let me know if it helps:
1. Internal Resource View Resolver
Your Internal Resource View Resolver looks for files with suffix .htm in jsp folder. Hence all your files, except index.jsp, should end with .htm. Or if they are .html, you can change the View Resolver to look for .html instead.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".html" />
</bean>
2. Input Type Button not Submit
Change the Input Type to just Button and not Submit.
On Click of this Input[type="Submit"], tends to submit the form to the action of the form(which isn't specified hence reloads the page which is why you get the same syso).
You want to override this input with your onclick event. Hence change it's type to button.
<INPUT id="button" TYPE="Button" VALUE="Submit">
3. Consumes and Produces
Not really required.
Those are basically restrictions on the handlers.
It was giving me trouble. It works without them. Totally your call on this one.