What am I using?
- Tomcat 7.0.56
- JAVA 1.8
- Spring MVC
- jQuery
What is the goal?
I'm implementing a content directory.
The user searches for a specific name or phone number for example. Then a list of contacts shows up on the left side of the page. On the right side there should details be displayed of a contact that gets selected.
Where is the problem?
My problem lays on the part of showing the details.
My Code:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html >
<%@ include file="includes/header.jsp" %>
<body>
<div class="pageContainer container-fluid">
<div class="row">
<%@ include file="searchBar.jsp" %>
</div>
<div class="row">
<div class="containerOverView col-lg-5 col-md-6 col-sm-12 col-xs-12">
<%@ include file="overView.jsp" %>
</div>
<div class="containerDetailView col-lg-7 col-md-6 col-sm-12 col-xs-12">
<%@ include file="detailView.jsp" %>
</div>
</div>
</div>
</body>
</html>
detailView.jsp
<ul class="flex-container">
<li class="flex-item-photo">Photo</li>
<li class="flex-item-pdetails">Personal Details</li>
<li class="flex-item-cdetails">Company Details</li>
<li class="flex-item-map">Map:
${detailSearchResult.name}
</li>
</ul>
MainController.java
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
@RequestMapping(value = "/refreshDetail", method = RequestMethod.POST)
@ResponseBody
private String refreshDetailView(HttpServletRequest hsr, @RequestParam String id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id));
return "detailView";
}
main.js
$(document).ready(function(){
$(".overViewListEmployee").click(function () {
var id = $(this).find(".overViewEmployeeID").text();
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accepts: "text/plain",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/refreshDetail",
data: ({"id" : id}),
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
});
What exactly doesn't work?
It seems to me, that the ajax request doesn't really get a valid response. From my understanding ajax accepts every kind of response but somehow, when I debug the JavaScript it says that the response has a Response Error: response is not defined
Error Codes:
With the code above:
400: Failed to load resource: the server responded with a status of 400 (Bad Request)
When I comment out following line in main.js:
//contentType: "application/json; charset=utf-8",
406: (Not acceptable)
What does work? (due to debugging)
When I debugged the code I saw that the value of the id is getting into the Controller correctly and also the function Dao.getDetailView(id)
works properly. So it's really just an issue of the response.
What else have I tried?
I'm not sure if it works that way, by returning a string with the name of the detailView.jsp page that should be reloaded since I don't know if the model I'm adding the attribute to is also going with it and rendered in the index.jsp (where detailView.jsp is included).
So I also tried to put the Controller-Function like this:
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
@RequestMapping(value = "/refreshDetail", method = RequestMethod.POST)
private ModelAndView refreshDetailView(@RequestParam String id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id));
return new ModelAndView("detailView");
}
and removing this line from main.js:
accepts: "text/plain",
I also tried by returning the model as well:
return new ModelAndView("detailView", model);
I'm not working with JavaScript that often, so it's possibly a really silly and obvious mistake but I can't seem to find it. I literally tried out everything I could find but it looks like I'm stuck here.
I would really appreciate any kind of help on this case :)
Update:
main.js
$(".overViewListEmployee").click(function () {
var id = parseInt($(this).find(".overViewEmployeeID").text());
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accept:"text/html",
//contentType: "application/json; charset=utf-8",
dataType: "html",
url: "/refreshDetail",
data: ({"id": id}),
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
MainController.java
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
@RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
private ModelAndView refreshDetailView(HttpServletRequest hsr, @RequestBody IdObject id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id.getId()));
return new ModelAndView("detailView", model);
}
IdObject.java
public class IdObject {
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Right now the Controller isn't reached at all - still got that 415 Error.
Update 2:
WebInit.java (before)
@Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer{
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebInit.java (after)
@Configuration
public class WebInit implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(RootConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Now I'm not sure if it's what you meant but from what I read @AnnotationDrivenConfig
is the same as to do it with AnnotationConfigWebApplicationContext
. And since I'm doing it with pure Java based Configuration I figured, that'd be my way to go.
But I still got the same error though.
WebConfig.java
@Configuration
@EnableWebMvc
@ComponentScan("com.avectris.newtel")
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/view/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/sass_compiled/**").addResourceLocations("/sass_compiled/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.extendMessageConverters(converters);
}
}