"no mapping found" error java spring MVC with no xml configuration - java

i'm new in Spring + MVC.
i've found a script and i could run some part of this script.
this script configuring spring mvc with no xml, inside java side.
i put all the jars into WEB-INF/lib.
ControllerConfiguration .java
package org.java.springmvc.bootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "org.java.springmvc.controller")
public class ControllerConfiguration {
#Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
WebAppInitializer.java
package org.java.springmvc.bootstrap;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(final ServletContext servletContext) throws ServletException {
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setServletContext(servletContext);
root.scan("org.java.springmvc.bootstrap");
root.refresh();
final Dynamic servlet = servletContext.addServlet("spring", new DispatcherServlet(root));
servlet.setLoadOnStartup(1);
servlet.addMapping("/*");
}
}
HomeController.java
package org.java.springmvc.controller;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping(value = "/")
public void home(final Writer writer)
throws IOException {
writer.append("<h2>Welcome, XML Free Spring MVC!</h2>");
}
#RequestMapping(value = "/giris")
public void giris(final Writer writer)
throws IOException {
writer.append("Giris");
}
}
FilmController.java
package org.java.springmvc.controller;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.java.springmvc.model.Film;
import org.java.springmvc.model.Film.FilmTurleri;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/film")
public class FilmController {
#RequestMapping(value = "filmler")
public void filmler(final Writer writer)
throws IOException {
writer.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-9\"><title>...Filmler...</title>");
writer.append("<script type=\"text/javascript\" src=\"/js/touch/sencha-touch-all.js\"></script>");
writer.append("<script type=\"text/javascript\" src=\"/js/film/filmler.js\"></script>");
writer.append("</head><body></body></html>");
}
#RequestMapping (value = "/filmleriGetir", method = RequestMethod.GET)
public #ResponseBody Map<String, List<Film>> FilmleriGetir() {
List<Film> movies = new ArrayList<Film>();
// For testing...
movies.add(new Film(0, "Birinci Film", "Birinci Yönetmen", 2015, FilmTurleri.Aksiyon));
movies.add(new Film(0, "İkinci Film", "İkinci Yönetmen", 2015, FilmTurleri.Komedi));
movies.add(new Film(0, "Üçüncü Film", "Üçüncü Yönetmen", 2015, FilmTurleri.Aile));
Map<String, List<Film>> resp = new HashMap<String, List<Film>>();
resp.put("filmListesi", movies);
return resp;
}
}
Film.java
package org.java.springmvc.model;
public class Film {
public int Id;
public String FilmAdi, Yonetmen;
public int CikisTarihi;
public FilmTurleri Turu;
public enum FilmTurleri {
Aksiyon, Komedi, Aile, Korku, Savas;
}
public Film(){
}
public Film(int id, String title, String director, int yearOfRelease, FilmTurleri tur)
{
super();
this.Id = id;
this.FilmAdi = title;
this.Yonetmen = director;
this.CikisTarihi = yearOfRelease;
this.Turu = tur;
}
//getter, settings method
}
i have two questions:
if i write "http://localhost:8080/SpringMVC/", the page displays.
But if i write "http://localhost:8080/SpringMVC/movies/index" i get this warning:
"WARNING: No mapping found for HTTP request with URI [/SpringMVC/WEB-INF/views/index.jsp] in DispatcherServlet with name 'spring'"
if i add a JSP page(Giris.jsp) under WebContent, i cannot display this page. must all page has a mapping? how can i display simple jsp page?
WARNING: No mapping found for HTTP request with URI [/SpringMVC/Giris.jsp] in DispatcherServlet with name 'spring'
EDIT:
i changed a little.
My project structure like this:
i get this error:
Failed to load resource:
http://localhost:8080/js/film/filmler.js
http://localhost:8080/js/touch/sencha-touch-all.js
i thought a logic like that:
- there will be a jsp file including "*.js" files. (filmler.jsp)
- there are some methods returning json object in those *.js files. (FilmleriGetir method)
any advice for this logic?
Regards.

In MovieController.java, you need to add '/'
:
#RequestMapping("/movies")
You are using servlet.addMapping("/*"); which means your org.springframework.web.servlet.DispatcherServlet i.e Spring will intercept every request that comes to your application. Now, you don't have any RequestMapping for Giris.jsp in any controller, so Spring is throwing error as: No mapping found for HTTP request with URI [/SpringMVC/Giris.jsp]
In order to show Giris.jsp page, your need to:
A] Add entry in/ make new controller with RequestMapping for 'Giris.jsp', and set view as 'Giris'
eg:
#Controller
public class MyController {
#RequestMapping(value = "/Giris.jsp")
public void home(final Writer writer)
throws IOException {
return 'Giris';
}
}
You would be better of using RequestMapping as /giris instead of /Giris.jsp, as it exposes that underlying technology is JSP.
B] place Giris.jsp file under /WEB-INF/views/ folder.
Understand how InternalResourceViewResolver works. Taking reference of your ControllerConfiguration, When a view name is returned for controller as 'Giris', InternalResourceViewResolver adds prefix and suffix as defined by you, and that page is shown. So, in case of view name 'Giris', page '/WEB-INF/views/'+ 'Giris' + '.jsp' will be rendered.
According to java naming convention, JSP (file) name should always begin with a lower-case letter. So use giris.jsp instead of Giris.jsp
EDIT(For modified question):
Failed to load resource: http://localhost:8080/js/film/filmler.js
Understand that, as DispatcherServlet is mapped to /*, every request that comes to your web-app, is handled by DispatcherServlet i.e Spring.
Whenever you application comes across url http://localhost:8080/js/film/filmler.js, it knows that DispatcherServlet will handle that url. DispatcherServlet checks if there is any RequestMapping for the url(in controller).
Now, when you add url
http://localhost:8080/js/film/filmler.js
there is no RequestMapping that would handle such kind of url, so you are getting a url.
For loading resources such as js files or image files, use mvc:resources.
eg:
For js files:
Put all your js files in directory /WEB-INF/js/.
Add mvc:resource mapping for js files in you configuration:
<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
Now you you will be able to access your js files. If Spring comes across url such as /js/film/filmler.js, it will know know from mvc:resource mapping, for where to look for that file.
Goof mvc:resource for tutorials.

Related

Nested Params in Spring Controllers is asking for Neting in JSP file Path. How to deal with that?

So this is my controller code :
`
package org.inventorymanagement.controller;
import org.inventorymanagement.databaseservice.BorrowBookDatabaseService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class BorrowPageController {
#RequestMapping(value = "/borrow/{bookName}/{issuerName}", method = RequestMethod.GET)
public ModelAndView searchForBookName(#PathVariable("bookName") String bookName, #PathVariable("issuerName") String issuerName) {
ModelAndView mav = new ModelAndView("borrow.jsp");
String rs = (String) new BorrowBookDatabaseService().borrowBookFromBookTable(bookName, issuerName);
return mav;
}
}
Here is the error which i am seeing on my webpage:
JSP file [/borrow/ABC/borrow.jsp] not found
ABC is my bookName.
Any suggestions how can i overcome it ?
I tried to change the path of jsp inside ABC folder and it works fine. But since ABC is generic how many folders i will made ?

I keep getting "Error: connect ECONNREFUSED 192.168.0.29:8080 " On postman console while im trying to make a get request on sts4

I have been trying all possible urls but same error keeps showing. please help. thanks in advance
here is my controller
package com.springstad.stad.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.springstad.stad.entitites.Names;
import com.springstad.stad.services.NameService;
#RestController
public class MyController {
#Autowired
private NameService nameservice;
// get employee names
#RequestMapping(path="/Names",method = RequestMethod.GET)
public List<Names> getNames(){
return this.nameservice.getNames();
}
#RequestMapping(path="/names/{nameID}",method = RequestMethod.GET)
public Names getNames(#PathVariable("nameID") String nameID) {
return this.nameservice.getNames(Long.parseLong(nameID));
}
}
what proxy config must i do for the postman to get responses from the code? ive been using localhost:8080/Names as url
Assuming its Spring-Boot app, pls check for servlet: context-path in application.yml (or application.properties). Lets say its value is "app1", then try with following url
localhost:8080/app1/Names

Send Multipart and JSON data in a Java Object - Spring Boot Rest

I have a java bean which has both multipart and String data. I am trying to pass it in a rest client call which takes this java bean input and processes it.
Below are my model class, controller and rest client.
On making a call from my rest client , I am getting this exception.
Exception in thread "main" org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [com.techidiocy.models.NHPdfMergeRequest] and content type [multipart/form-data]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:810)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:594)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:384)
Model Class
import org.springframework.web.multipart.MultipartFile;
public class Candidate {
private String firstName;
private String lastName;
private MultipartFile resume;
//getters and setters
}
Controller Class
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
#RestController
public class CandidateController {
#Autowired
private CandidateService candidateService;
#RequestMapping(method=RequestMethod.POST, path="/add")
public void add(#RequestBody Candidate request) {
// do some processing
String firstName = request.getFirstName();
String lastName = request.getLastName();
MultipartFile resume = request.getResume();
candidateService.add(firstName, lastName, resume);
}
}
Rest Client
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.client.RestTemplate;
public class CandidateClient {
public static void main(String[] args) throws IOException {
String serverURL = "http://localhost:8080/add";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
Candidate candidate = new Candidate();
candidate.setFirstName("John");
candidate.setLastName("Doe");
candidate.setResume(new MockMultipartFile("tmp.pdf", FileUtils.readFileToByteArray(new File("/home/john/resume/john.pdf"))));
HttpEntity<Candidate> httpEntity = new HttpEntity<Candidate>(candidate, headers);
RestTemplate client = new RestTemplate();
client.postForEntity(serverURL, httpEntity, Resource.class);
}
}
Note: I had also tried to set the header content type as json in rest client and then I am getting all the values as Null in the controller. headers.setContentType(MediaType.APPLICATION_JSON);
I had also searched over the internet for this kind of scenario but I am unable to find a solution for this.
I had also tried to pass all the parameters separately (not as part of java bean) then I am able to make it work.

How do I call MitreID OIDC server?

I am using the Spring Boot MitreID OIDC application from here. This runs OK and I can login but there are no other options available to me:
I am trying to access it using simple-web-app. In simple-web-app I try to login using URI: http://localhost:8080/openid-connect-server-webapp/. This gives:
WARN : org.mitre.openid.connect.client.service.impl.DynamicServerConfigurationService -
Couldn't load configuration for http://localhost:8080/openid-connect-server-webapp/:
com.google.common.util.concurrent.UncheckedExecutionException:
org.springframework.web.client.HttpClientErrorException: 404
ERROR: org.mitre.openid.connect.client.OIDCAuthenticationFilter - No server
configuration found for issuer: http://localhost:8080/openid-connect-server-webapp/
EDIT: when I try http://localhost:8080 I get:
WARN : org.mitre.openid.connect.client.service.impl.WebfingerIssuerService - Webfinger
endpoint MUST use the https URI scheme, overriding by configuration
ERROR: org.mitre.openid.connect.client.OIDCAuthenticationFilter - No client
configuration found for issuer: http://localhost:8080/
Can anyone point me in the right direction?
FYI simple-web-app has only one java class:
package org.mitre.web;
import java.security.Principal;
import java.util.Locale;
import java.util.Set;
import javax.annotation.Resource;
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
// filter reference so we can get class names and things like that.
#Autowired
private OIDCAuthenticationFilter filter;
#Resource(name = "namedAdmins")
private Set<SubjectIssuerGrantedAuthority> admins;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model, Principal p) {
model.addAttribute("issuerServiceClass", filter.getIssuerService().getClass().getSimpleName());
model.addAttribute("serverConfigurationServiceClass", filter.getServerConfigurationService().getClass().getSimpleName());
model.addAttribute("clientConfigurationServiceClass", filter.getClientConfigurationService().getClass().getSimpleName());
model.addAttribute("authRequestOptionsServiceClass", filter.getAuthRequestOptionsService().getClass().getSimpleName());
model.addAttribute("authRequestUriBuilderClass", filter.getAuthRequestUrlBuilder().getClass().getSimpleName());
model.addAttribute("admins", admins);
return "home";
}
#RequestMapping("/user")
#PreAuthorize("hasRole('ROLE_USER')")
public String user(Principal p) {
return "user";
}
#RequestMapping("/open")
public String open(Principal p) {
return "open";
}
#RequestMapping("/admin")
#PreAuthorize("hasRole('ROLE_ADMIN')")
public String admin(Model model, Principal p) {
model.addAttribute("admins", admins);
return "admin";
}
#RequestMapping("/login")
public String login(Principal p) {
return "login";
}
}
MitreID is serving on root but sample app is calling on /openid-connect-server-webapp/
You'll want to change your sample app to point to the proper issuer....http://localhost:8080/ (maybe in the application.properties of your sample app?) Or your MitreID server is not configured properly (possibly for issuer property)
See http://localhost:8080/.well-known/openid-configuration for all the endpoints your sample app would hit

Whitelabel Error Page after refresh

I have Spring Boot Application (backend) and for the Frontend I am using the Angular 2 Single Page Application.
Whenever I navigate to a route for example: localhost:8080/getAccounts and do after the navigation a refresh I get the Whitelabel Error Page. If I am at the root localhost:8080 I works fine. The problem only occurs in the sub links.
Returning (use the return/back button) to the previous page also works fine. Just the refresh.
I also can not call direct the link: localhost:8080/getAccounts. First I have to go to Home (localhost:8080) an call the page throug sub navigation bar.
Does anybody had the same problem? What excalty I do have to change. My Code:
Main.ts
import {bootstrap} from '#angular/platform-browser-dynamic';
import {AppComponent} from './components/app.component';
import {HTTP_PROVIDERS};
import {enableProdMode} from '#angular/core';
enableProdMode();
bootstrap(AppComponent, [HTTP_PROVIDERS]);
app.comonent:
import { Component, OnInit } from '#angular/core';
import { Http } from '#angular/http';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '#angular/router-deprecated';
import { HomeComponent } from './home.component';
import { UserSearchComponent} from './webUserProfiles.component';
import { UserDetailViewComponent} from './webUserProfileView.component';
import { HTTPService } from '../service/http.service';
#Component({
selector: 'app-content',
templateUrl: './app/templates/app.component.html',
directives: [ROUTER_DIRECTIVES, AccessErrorComponent],
providers: [
ROUTER_PROVIDERS,
HTTPService
]
})
#RouteConfig([
{
path: '/',
name: 'HomeComponent,
useAsDefault: true
},
{
path: '/user',
name: 'UserSearch',
component: UserSearchComponent,
},
{
path: '/user/:id',
name: 'UserDetailView',
component: UserDetailViewComponent,
}
])
export class AppComponent implements OnInit {
constructor (
) { }
}
}
Thanks in advance
After some researches, i found this pretty good answer from Thierry Templier
With the default strategy (HTML5 history API) of routing, you need a server configuration to redirect all your paths to your HTML entry point file. With the hashbang approach it's not necessary... If you want to switch to this approach, simply use the following code:
import { bootstrap } from "angular2/platform/browser";
import { provide } from "angular2/core";
import {
ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy
} from "angular2/router";
bootstrap(MainApp, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass:HashLocationStrategy});
]);
You could have a look at these questions about this issue:
When I refresh my website I get a 404. This is with Angular2 and firebase
PathLocationStrategy vs HashLocationStrategy in web apps
Is Angular 2's Router broken when using HTML5 routes?
I had a similar issue WhiteLabel Error message on my Angular SPA whenever I did a refresh.
If you don't want to change the app URL (which will happen if you use HashLocation Strategy), you could add a new controller to handle the White label Error mapping in your Spring Boot app.
The fix was to create a controller that implements ErrorController and return a ModelAndView object that forwards to /
#CrossOrigin
#RestController
public class IndexController implements ErrorController {
private static final String PATH = "/error";
#RequestMapping(value = PATH)
public ModelAndView saveLeadQuery() {
return new ModelAndView("forward:/");
}
#Override
public String getErrorPath() {
return PATH;
}
}
If you don't want to use the HashLocationStrategy, you can add the following controller in your project :
#Controller
public class UiController {
#GetMapping("/")
public String welcome() {
return "index.html";
}
// Match everything without a suffix (so not a static resource)
#GetMapping(value = {
"/{path:[^.]*}",
"/{path:[^.]*}/{path:[^.]*}",
"/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}",
"/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}",
"/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}/{path:[^.]*}"
// add more if required ...
})
public String redirect() {
// Forward to home page so that route is preserved.
return "forward:/";
}
}
Have one better way...
You can implement WebMvcConfigurer and add the view controller generic paths.
follow the example:
package net.mypackage.config;
import org.springframework.context.annotation.Configuration; import
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import
org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration public class MvcConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
String viewName = "forward:/";
registry.addViewController("/{spring:\\w+}")
.setViewName(viewName);
registry.addViewController("/**/{spring:\\w+}")
.setViewName(viewName);
registry.addViewController("/{spring:\\w+}/**{spring:?!(\\.js|\\.css)$}")
.setViewName(viewName);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
About the macther: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html

Categories

Resources