Trying to understand a sample code...
I am returning a modelview successfully from my AthuenticationController like this
modelAndView = new ModelAndView("redirect:/home/");
....
return modelAndView;
and my browser url is changed to /home/ but its showing a 404 page
I have a HomePageController and it has methods
#RequestMapping(method = RequestMethod.GET)
public String loadHome
and
#RequestMapping(method = RequestMethod.GET, value = "/main")
public String reloadHome
but System.out.println("Message") is not executing in any of the above methods.
When authenticated I want to load a home.jsp page? It is in WEB-INF/jsp/...
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
login.html page thats from WEB-INF/jsp/ is loading fine
Here is the update Now it is opeining WEB-INF/jsp/home.jsp page in browser but the url is still the old one...
You need to change request mapping
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String loadHome
instead of this
modelAndView = new ModelAndView("redirect:/home/");
....
return modelAndView;
try this one :
modelAndView = new ModelAndView("home");
....
return modelAndView;
Related
An AJAX-call is done to the Controller:
$.ajax({
cache : false,
type : "POST",
url : url,
data : {
//some data
}
That call is successfully interpreted by the controller:
#RequestMapping(value = "/checkIfRatedOverall")
public ModelAndView checkIfRatedOverall(#ReqestParam.......)
But when i return the ModelAndView nothing happens!
The view stays the same and the browser does not display xxx.jsp
return new ModelAndView("xxx"); //NOTHING HAPPENS
LOG:
JstlView:166 - Forwarding to resource [/WEB-INF/views/xxx.jsp] in InternalResourceView 'xxx'
DispatcherServlet:1251 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'xxx'
DispatcherServlet:1000 - Successfully completed request
your internal view resolver should be like this
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Check ajax documentation here
$.ajax({ ...}).done(
function( html ) {
$( "#results" ).append( html );
});
What you do with the ajax response? From what I see you are doing nothing with server response.
Use #ResponseBody Attribute and return JSON object instead of model view
#RequestMapping(value = "checkIfRatedOverall", method = RequestMethod.POST)
public #ResponseBody String checkIfRatedOverall(#ReqestParam.......)
{
return jsonStr://return json string
}
In jquery parse the string with JSON.parse(data)
$.ajax({
cache : false,
type : "POST",
url : url,
data : {
//some data
},
success : function(data) {
JSON.parse(data);
}
});
I am new to String, and now facing some staring issues with Spring MVC.
In my application I have view resolver which maps view names to respective JSP files.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/pages/</value></property>
<property name="suffix"><value>.jsp</value></property>
<property name="order" value="1" />
</bean>
It is working as expected, but now need to call a method in controller and show returned string in view.
my URL of request looks like http://localhost:8015/demo/greet
And the method in my controller to server this request is
#RequestMapping("/greet")
public String user(User user) {
return "Hi User";
}
When i call this url from browser, given method in browser get invoked, and when it returns a string, InternalResourceViewResolver try to find a page /WEB-INF/pages/greet.jsp, and as it doesn't exist, user gets 404 error. How can i send raw String from my controller method to browser?
Just change your controller code as below
#RequestMapping("/greet")
public #ResponseBody String user(User user) {
return "Hi User";
}
See documentation of ResponseBody here
Try:
#RequestMapping("/greet")
public #ResponseBody String user(User user) {
return "Hi User";
}
I have configured my spring project to cater to static resources using below settings in XML file:
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
But when I try to access the static content directly, say using below URL:
http://localhost:8080/main/resources/css/app.css
Instead of showing up the static CSS content in the browser, the request is going to the following method in Controller:
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
Once the request leads to this method instead of showing up the staic CSS file, I see the JSP page returned by return call "home".
I have checked and rechecked but dont really sight any issue with set up.
Please have a look and let me what might be going wrong here.
Below is the Main Controller that my application is using.
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class MainController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String country(Locale locale, Model model) {
System.out.println("nothing but home page");
return "home";
}
#RequestMapping(value = "/{countryID}", method = RequestMethod.GET)
public String country(#PathVariable("countryID") String countryID, Locale locale, Model model) {
System.out.println("input country "+countryID);
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}", method = RequestMethod.GET)
public String state(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}/{destId}", method = RequestMethod.GET)
public String dest(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, #PathVariable("destId") String destId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
System.out.println("input "+destId);
model.addAttribute("serverTime", "");
return "home";
}
}
And below is the application XML file :
<?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/" />
<!-- <beans:bean class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/views.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean> -->
<!-- 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.travel.main" />
</beans:beans>
The problem is, your #RequestMapping in the controler has precedence over the resource-mapping. To change this, you have to do two things:
Add the attribute order="0" to your resources-tag.
Change the order of your tags to:
<resources mapping="/resources/**" location="/resources/" order="0" />
<annotation-driven />
Then it should work.
It seems http://localhost:8080/main/resources/css/app.css is mapped to /{countryID}/{stateId}/{cityId}:
countryId=resources
stateId=css
cityId=app.css
It seems the resources are only mapped when there is no Controller that matches the URL, so you can try to add to that controller a different path: You can change #RequestMapping("/") to #RequestMapping("/mainController") or add something like /city/ in the matcher of the city method: city/{countryID}/{stateId}/{cityId}.
Give a try the following options:
Remove #RequestMapping("/") from the MainController.
Add a View Resolver to your Spring configuration. For instance, InternalResourceViewResolver.
Take a look at the Spring doc.
Move the resources directory to the same level as views. That is,/WEB-INF/views and /WEB-INF/resources.
I hope that helps!
I am trying to run a simple controller with a method that will receive
A String with a value
A file (MultipartFile object)
After some investigation (Sending Multipart File as POST parameters with RestTemplate requests) I ended up adding into my web.xml
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/REST/*</url-pattern>
</filter-mapping>
My application context file
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
The controller looks like
#Controller
#RequestMapping("/image")
public class ImageController extends RestApiController {
private static final Logger log = LoggerFactory.getLogger(ImageController.class);
#RequestMapping(value="/simple", method = RequestMethod.POST, consumes="multipart/form-data")
public #ResponseBody boolean save(
#RequestParam(value = "file", required = false) MultipartFile file,
#RequestParam(value = "name", required = false) String name) {
//Some code here
return true;
}
So far I have been able to run unit tests against the controller with no problem, but I seem to be stuck when it comes to create a real http request.
I have tried with POSTMAN, but after some investigation seems that it does not set the multipart/form-data header properly, I have tried removing it, and the problem persists.
I have also tried with CURL
curl http://127.0.0.1:8080/content/REST/image/simple -F "file=#/home/jmoriano/Pictures/simple.jpeg" -F "name=someName" -v
I have also tried with a RestTemplate object
public Boolean update() {
RestTemplate restTemplate = new RestTemplate();
try {
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource("/home/jmoriano/Pictures/simple.jpeg"));
parts.add("name", "name");
return restTemplate.postForObject("http://127.0.0.1:8080/content/REST/image/simple", parts, Boolean.class);
} catch (Exception e) {
e.printStackTrace();
log.error("Ouch!", e);
}
return false;
}
Just to be clear, the problem is not in the "name" parameter, that one works fine, however the MultipartFile is empty.
By debugging the code, I managed to check the MultiPartFilter class which receives an HttpServletRequest object, such object has its "parts" attribute already empty there. So the problem seems to be related with the way I am making the request... seems that my postman/curl/java attempts have failed... do you see anything incorrect in my config?
I think you should put the bean multipartResolver to your dispathcher-servlet.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
in the link you show above they use this bean, too.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
I am creating a login form in Spring MVC. My spring version is 4.0.6.
I have configured my properties file ApplicationResources.properties like below
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:ApplicationResources</value>
</list>
</property>
</bean>
I am able to read value of lables defined in property file by using tag lib like below
<spring:message code="ui.label.username" />
But I am facing problem with validation below is the controller class method.
#RequestMapping(value = "/doLogin.spr" , method=RequestMethod.POST)
public String login(#Valid LoginForm loginForm, BindingResult bindingResult, HttpServletRequest request, Model model) {
try{
if(bindingResult.hasErrors()){
model.addAttribute("command", loginForm);
return "login" ;
}
User user = loginService.login(loginForm.getUserName(), loginForm.getPassword());
return "login" ;
}catch (Exception e) {
// TODO: handle exception
return "login" ;
}
}
In my validator I am validating field like below
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "app.ui.userName.error");
In my property file I have defined labels like below.
app.ui.userName.error.loginForm.userName=First UserName
app.ui.userName.error.userName=Second UserName
app.ui.userName.error.java.lang.String=String UserName
app.ui.userName.error=Simple error
On JSP I am trying to access error like below
<form:errors path="userName"/>
But I am not able to see error message on my UI. What could be problem here.