I have this code in my Spring Boot Application
#RestController
public class SampleController {
public SampleController() {
File file = new File("restresources");
System.out.println("File -> "+ file.getAbsolutePath());
}
#GetMapping(value = "/sample")
public String sampleText(HttpServletRequest request){
System.out.println("Sample Text");
return "Sample Text";
}
#RequestMapping()
public String acceptAny(){
return "ASDasdasdasdasd";
}
}
The acceptAny Method accepts any url hit from browser? But I have react files in my public folder too. So, when I hit localhost:8090/, instead of loading react index.html, it loads acceptAny() method.
How can I load react index.html instead of invoking this acceptAny() method or is there any method for loading React index.html from Controller itself?
Any help is highly appreciated!
first of all you have remove method acceptAny is hasn't any useful duties.
Than you should build your reactjs project and copy build files in resources/public or resources/static, than run project and open in browser localhost:8090/
Related
I have made a code using spring boot and itextpdf 5, actually I am trying to do something like this example
https://github.com/aboullaite/SpringBoot-Excel-Csv
my code is working fine when I run it in my STS IDE, but it shows error as error resolving template when I create jar file and run it, can anyone please help
Edit:- I am using thymeleaf for html view
Code
this is my webconfig class
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true).ignoreAcceptHeader(true);
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolvers.add(excelViewResolver());
resolvers.add(pdfViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
#Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
/*
* Configure View resolver to provide Pdf output using iText library to
* generate pdf output for an object content
*/
#Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
}
}
and here are my controller methods
#GetMapping( "/download")
public String download(Model model) {
model.addAttribute("cards", new StudentsDto());
return "getReportCard";
}
#PostMapping("/download")
public String postReportCard(#ModelAttribute("cards") StudentsDto cards, Model model){
List<Students> sList=studentService.searchByClassSectionBySession(cards.getClassSection(), cards.getSession());
model.addAttribute("studentsList", sList);
return "";
}
My question is , If everythinbg is working fine on running code as spring boot application through my STS IDE then why the jar I have created is not showing pdf views ?
I have created jars from my sts ide, i did maven clean and then i created jar using maven install
Solved
Was a stupid mistake, I don't kn how but in my template folder I changed the name of file getReportCard.html as getReportCArd.html.
Was a silly mistake and I checked upon each and every possible configuration. :-)
I want only to edit Spring White Label Page. I see a lot of tutorials for deleting this page, but I want only to change some text here, for example Error 404 - Go back! Any tutorial?
Thanks!
If you are using Spring Boot version 1.4+, custom error pages may be named according to their appropriate error code (e.g. 404.html) and placed in the /src/main/resources/public/error directory for static files or the /src/main/resources/templates/error directory if using a template engine. See Spring Boot and custom 404 error page for more details. You may alternatively follow the steps below to implement custom error pages.
Set the server.error.whitelabel.enabled property to false in your application.properties file. This will disable the error page and show an error page originating from the underlying application container.
server.error.whitelabel.enabled=false
Create custom error pages and save them in resources/templates directory. These pages may be created and named for different HTTP status codes, e.g.: error-404, error-500, etc.
Create a new Controller class that implements the ErrorController interface and override the getErrorPath method. Create a mapping for the path returned by the getErrorPath method. The method that handles this mapping can read the error code and return the appropriate custom error page.
#Controller
public class MyErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
#RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status =
request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if(statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404";
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()){
return "error-500";
}
}
return "error";
}
#Override
public String getErrorPath() {
return ERROR_PATH ;
}
}
I have an error page in vaadin UI. But sometimes we can write a wrong url and we see the springboot error page.
I want to show vaadin UI error page in this case. By the way, I have already have a rendered 404 page for springboot. But I don't want to show it.
This is my vaadin error UI. But this works into the application. (http://localhost:7001/MyApplication/#!error)
sometimes I write an invalid url like this: http://localhost:7001/MyApplication/blablablabla
in this case I want to redirect vaadin error page (http://localhost:7001/MyApplication/#!error) But the springboot redirects me to rendered 404 page.
It is possible?
#UIScope
#SpringView(name = ErrorView.VIEW_NAME)
public class ErrorView extends VerticalLayout implements View {
public static final String VIEW_NAME = "error";
private Label explanation;
public ErrorView() {
Label header = new Label("The view could not be found");
header.addStyleName(MaterialTheme.LABEL_H1);
addComponent(header);
addComponent(explanation = new Label());
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
explanation.setValue(String.format("You tried to navigate to a view ('%s') that does not exist.", event.getViewName()));
getUI().getNavigator().navigateTo(ErrorView.VIEW_NAME);
}
}
you can put 404/500 page under resources/error/ folder, Spring boot will redirect those page automatic when have error
I think SpringNavigator can solve your problem. While defining your Navigator, you can also define error View. See the example below
#SpringUI(path = "ui")
public class DemoUI extends com.vaadin.ui.UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
SpringNavigator navigator = new SpringNavigator();
navigator.setErrorView(new ErrorView());
setNavigator(navigator);
}
}
I have a Spring Boot project, what I deployed on remote server. When I call http://109.206.178.66:8080/proxynator/ - I can see an index.html, but when I call rest controller by url http://109.206.178.66:8080/proxynator/countries - I have an error 404 whith
Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
It's strangely, because when I start this project on my local machine, all working right. Project structure is:
Line from catalina.out file:
SEVERE [http-nio-8080-exec-19] org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml Parse error in application web.xml file at [file:/opt/tomcat/webapps/proxynator/WEB-INF/web.
My controller:
#RestController
class MainController(val proxyRepo: ProxyRepo, val countryRepo:
CountryRepo) {
#GetMapping("/countries")
fun findCountries(): List<Country> = countryRepo.findAll()
#GetMapping("/proxies")
#ResponseBody
fun findProxies(#RequestParam countryid: Int): List<Proxy> =
proxyRepo.findAllByCountryid(countryid)
}
UPD
I added configuration class on the root package
#Configuration
open class RestConfiguration {
#Bean
open fun mainController():MainController
= MainController()
}
But it does not working. I don't understand, why I can see index.html by irl http://109.206.178.66:8080/proxynator/, but can't get access to my controllers. When I package my project I have some files:
Any advice?
your api access url is wrong access using http://109.206.178.66:8080/countries this is the correct path for your rest mapping, not http://109.206.178.66:8080/proxynator/countries
To solve this problem I was edit my Application class.
#SpringBootApplication
#EnableAutoConfiguration
open class Application: SpringBootServletInitializer(){
#Override
override fun configure(application: SpringApplicationBuilder?):
SpringApplicationBuilder {
return super.configure(application)
}
}
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
I was override configure method, and all is working!
Hope it will save time for anybody!
With the fine way to serve static html/css/js resources from src/main/resources/static, is there a way to have some form of url abstraction?
Precisely, I would like to remove the .html ending from the urls.
To return html static file without extension is the same as return view name from any of templates engines (jsp, theamleaf, freemarker), the thing here you do not need to run any templates processing on view file, you just return it as it is.
Add code below to your Spring configuration:
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("pages/");
internalResourceViewResolver.setSuffix(".html");
return internalResourceViewResolver;
}
Be careful /pages folder should be inside your ResourceLocation
, that means ResourceLocation + "/pages/" + pageName.html in browser should give you desired file (if you already configured servicing of static files it will not be a problem for you to find your ResourceLocation, check method addResourceHandlers in your WebMvcConfigurer)
Now at your WebMvcConfigurer you can add:
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/admin").setViewName("admin");
registry.addViewController("/contact").setViewName("contact");
registry.addViewController("/error").setViewName("index");
}
or just use it, as you would use it in usual view resolver within MVC controller
#GetMapping("/")
public String greeting() {
return "index";
}
A request mapping that ignores all URLs that have a file extension and adds .html to URLs with no file extension.
#Controller
...
#RequestMapping("/{page:^(?!.*[.].*$).*$}")
public String requestOther(#PathVariable("page") String page) {
return "/"+page+".html";
}
...
Change the "/" to a sub directory if needed e.g. "/pages/".