Webapp needs to serve static content and process rest calls on the seperate path.
In config I have registered ResourceHttpRequestHandler and Dispatcher Servlet:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/index.html").addResourceLocations("index.html");
}
#Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addUrlMappings("/rest/*");
return registration;
}
#Bean(name = "dispatcherServlet")
public DispatcherServlet dispatcherServlet(WebApplicationContext context) {
return new DispatcherServlet(context);
}
But the problem is that reource handler is not invoked if dispatcher servlet is registered, if I remove dispatcher servlet resource serving works.
How to get around this problem?
Maybe I should serve static content also with dispatcher servlet?
Related
I'm getting this error when trying to post JSON data from angularjs controller to SpringMVC controller. I've tried a lot of solutions posted here and some other stuff available on the net as well. I already have the jackson library in my classpath. And also I'm not using maven because of internet issues.
SpringMVC Controller
#Controller
public class MainController {
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping(value = "/employee", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String saveEmployee(#RequestBody Employee employee) {
//Will do some stuff here.
System.out.println("INSIDE CONTROLLER");
StringBuilder json = new StringBuilder();
return json.toString();
}
}
AngularJS Controller
app.controller('saveEmployeeCtrl', function ($scope, $http) {
$scope.employee = {};
$scope.saveEmployee = function () {
$http({
method: 'POST',
url: 'employee',
data: $scope.employee,
headers:{'Accept':'application/json', 'Content': 'application/json'}
}).success(function(data){
console.log('something nice');
});
};
});
WebConfig
#EnableWebMvc
#Configuration
#ComponentScan("springmvc.com.")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webapp/resources/static/app/**")
.addResourceLocations("/webapp/resources/static/app/");
registry.addResourceHandler("/webapp/resources/static/lib/**")
.addResourceLocations("/webapp/resources/static/lib/");
registry.addResourceHandler("/webapp/resources/static/js/**")
.addResourceLocations("/webapp/resources/static/js/");
registry.addResourceHandler("/webapp/resources/static/css/**")
.addResourceLocations("/webapp/resources/static/css/");
registry.addResourceHandler("/webapp/webapp/resources/static/views/**")
.addResourceLocations("/webapp/webapp/resources/static/views/");
registry.addResourceHandler("/webapp/resources/static/**")
.addResourceLocations("/webapp/resources/static/");
}
#Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true)
.parameterName("mediaType").ignoreAcceptHeader(true)
.useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebAppInitializer
public class WebAppInitializer implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "springmvc.com.config";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("***** Initializing Application for " + servletContext.getServerInfo() + " *****");
// Create ApplicationContext
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.setConfigLocation(CONFIG_LOCATION);
// Add the servlet mapping manually and make it initialize automatically
DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
servlet.addMapping("/");
servlet.setAsyncSupported(true);
servlet.setLoadOnStartup(1);
}
}
You are sending header "Content" but you should send "Content-Type"
Do you send exactly the same fields in JSON as there are in Employee class, check if there are no additional fields, because Jackson has setting that it fail if unrecognized field is set. And there are some resolutions for this issue (like annotation on your class or change this setting)
Most important is what appear in the log file of your server application. What exception is raised as a cause of this http status. So i the solutions above not helping you, please check logs (maybe increase log level for spring) and post it here.
UPDATE:
I have few additional questions:
has your Employee class got default (non args) constructor or maybe you create only constructor with arguments? Could you post your Employee class.
Do you have any logger attached to your project, is there anything in log file, (if there is, please post it)?
There are similar topics, but they all use xml configuration files. The reason why I'm writing this question is that I'm using annotations.
I experience problems running my app:
getting “WARN org.springframework.web.servlet.PageNotFound - No
mapping found for HTTP request with URI …” when trying to setup
Spring servlet
getting error 404 when trying to run it on server
Here is my code (package and imports are skipped):
1) initializer
public class WebInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
2) app config
#Configuration
#ComponentScan("ua.kiev.prog")
#EnableWebMvc
public class AppConfig {
#Bean
public EntityManager entityManager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("AdvJPA");
return emf.createEntityManager();
}
#Bean
public AdvDAO advDAO() {
return new AdvDAOImpl();
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolver.setOrder(1);
return resolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}
3) controller
#Controller
#RequestMapping("/Advertisement")
public class MainController {
#Autowired
private AdvDAO advDAO;
#RequestMapping("/")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
#RequestMapping(value = "/add_page", method = RequestMethod.POST)
public String addPage(Model model) {
return "add_page";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(#RequestParam(value="pattern") String pattern) {
return new ModelAndView("index", "advs", advDAO.list(pattern));
}
// more code goes here
}
The controller is mapped to /Advertisement, so app should be available at URL localhost:8080/Advertisement/ but it isn't. When I change mapping in annotation to "/" - it becomes available at localhost:8080/Advertisement/. How can it be?
And when I change it back to "/Advertisement" - the same probleb accurs (error 404 and exception "No mapping found for HTTP request with URI …")
So, where I've made a mistake in my code?
Or maybe the problem is in Eclipse/TomCat/Maven?
Source - https://github.com/KostyantynPanchenko/prog.kiev.ua.lesson09.adv
You should change mapping
#Controller
#RequestMapping("/")
public class MainController {
#Autowired
private AdvDAO advDAO;
#RequestMapping("/Advertisement")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
The mistake that a mapper used the value from the annotation to match the request URL, and it can't match the last slash. Note, it should not happen in the above code.
How are you running the application? Atleast in tomcat each deployed application is served from specific context path. Context path is determined from the base file name, more on that here.
So if you're deploying Advertisement.war all requests to the app will be served from localhost:8080/Advertisement/ even though you're declaring the DispatcherServlet and Controller to /
I using maven web application, framework spring.
Using Netbeans IDE and Tomcat server.
When I run web in netbeans, URL in browser is:
http://localhost:8080/mywebsite
With this URL website cannot read event servlet mapping.
When I change URL to http://localhost:8080/mywebsite/ then It run good.
What is reason for this case? Why my website don't auto add character "/" in URL?
{update}
config.java
public class Config extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/html/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/*");
}
}
Initializer
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
controller
#Controller
public class MyController {
//<editor-fold defaultstate="collapsed" desc="ADMIN">
#RequestMapping(value = "/", method = RequestMethod.GET)
public String login(ModelMap map) {
return "admin/login";
}}
If you open http://localhost:8080/mywebsite, the web app will try to find some index.html file(based on tomcat or http server configuration).
And you mapping is #RequestMapping(value = "/", method = RequestMethod.GET), so it will apply to http://localhost:8080/mywebsite/. If you want to use your controller to handle http://localhost:8080/mywebsite, you can try to use * in your mapping value. It means, for any request, if there is no specific mapping defined, and that default mapping will be applied.
I learn create Web Service soap from guide Producing a SOAP web service
When I have jar file and run main method everything is ok. I change to war file run by mvn spring-boot:run is the same.
But next i have a problem and I wont resolve it without use xml configuration (if I can) only annotation or java code
I found many similar issue but none was help
e.g
https://stackoverflow.com/questions/21115205/spring-boot-with-spring-ws-soap-endpoint-not-accessable
http://stackoverflow.com/questions/26873168/spring-boot-webservice-from-wsdl-not-working
Deploy war on wildFly 8.2 after that show wsdl but nothing else.
I change
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
to
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(WebServiceConfig.class);
}
}
and deploy in wildFly 8.2 after that show wsdl but when put request in SoapUI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:gs="http://spring.io/guides/gs-producing-web-service">
<soapenv:Header/>
<soapenv:Body>
<gs:getCountryRequest>
<gs:name>Spain</gs:name>
</gs:getCountryRequest>
</soapenv:Body>
</soapenv:Envelope>
get
WARN [org.springframework.ws.server.EndpointNotFound] (default task-7) No endpoint mapping found `for [SaajSoapMessage {http://spring.io/guides/gs-producing-web-service}getCountryRequest]`
and clear page in soapUI
I search similar issue e.g Endpoint not accessable
changed
#Bean
public ServletRegistrationBean dispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
to
#Bean
public MessageDispatcherServlet dispatcherServlet() {
return new MessageDispatcherServlet();
}
is the same, but when I use
#Bean
public MessageDispatcherServlet dispatcherServlet() {
return new MessageDispatcherServlet(getContext());
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new
AnnotationConfigWebApplicationContext();
context.setConfigLocation(Application.class.getName());
return context;
}
get
Caused by: java.lang.NoSuchMethodError: org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.applicationContext(Lorg/springframework/context/ApplicationContext;)Lorg/springframework/http/converter/json/Jackson2ObjectMapperBuilder;
whole error log and whole eclipse project
Thanks M. Deinum for reply it's really helpful.
First I tried use only Application class but I couldn't run server. Error in log Caused by: java.lang.ClassNotFoundException: org.xnio.SslClientAuthMode next I found solution with create two classes WebServiceConfig and Application.After changing server started , wsdl showed for me it was good change, therefore thank you again.
This issue is caused spring-boot bug GitHub, now I moving whole code from WebServiceConfig to Application and using the newest compile spring-boot. After that WS work good.In pom Paste current Application class maybe someone will have the same problem.
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletRegistrationBean dispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(
XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws/");
wsdl11Definition
.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(Application.class.getName());
return context;
}
}
In some methods from the controllers in my spring application, I have methods which return a String value to the view, like this example:
#RequestMapping(value="cadastra_campo", method=RequestMethod.GET)
public String cadastra_campo(#ModelAttribute("username") String username, #RequestParam("nome") String campo) {
if(key.temAutorizacao(key.getUsuarioByUsername(username).getId())) {
if(key.cadastra(campo))
return "yes";
else
return "not";
}
else {
return "no_permit";
}
}
But, monitoring the value received by the views, through the browser's console, I realize that all of them are trying reach out pages like /jst/yes.jsp.
this output is read in the view by jquery functions like that:
$("#incluir_campo").on("click", function () {
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/cadastra_campo"/>",
data: {nome: $("input[name=nome_campo]").val() }
}).done(function(data){
if(data=="yes") {
var newRow = $("<tr>");
cols = 'td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';
newRow.append(cols);
$("table.campos").append(newRow);
$("input[name=nome_campo]").reset();
}
else {
alert("erro ao incluir campo");
}
}).fail(function(){
alert("falha ao incluir campo");
});
});
I am using a java configuration in replacement to files web.xml and spring-servlet.xml, through this classes:
WebAppInitializer.java
#Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
#SuppressWarnings("resource")
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.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(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
WebAppConfig.java
#EnableWebMvc
#EnableTransactionManagement(mode=AdviceMode.PROXY, proxyTargetClass=true)
#ComponentScan(value="com.horariolivre")
#Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/bootstrap/**").addResourceLocations("/bootstrap/").setCachePeriod(31556926);
registry.addResourceHandler("/extras/**").addResourceLocations("/extras/").setCachePeriod(31556926);
registry.addResourceHandler("/jquery/**").addResourceLocations("/jquery/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Someone knows how to do for my views receive correctly a String value, instead of try reach a jsp page?
If you don't provide a ViewResolver in your context configuration available to the DispatcherServlet, it will use a default. That default is an InternalResourceViewResolver.
When your #RequestMapping handler method returns a String, Spring uses ViewNameMethodReturnValueHandler to handle it. It will set the returned String value as the request's view name. Down the line, Spring's DispatcherServlet will use the InternalResourceViewResolver to resolve a view based on the provided name. This will be a JSP. It will then forward to that JSP.
If you want to return the handler method's String return value as the body of the HTTP response, annotate the method with #ResponseBody. Spring will use RequestResponseBodyMethodProcessor to write the value to the HttpServletResponse OutputStream.