Spring-boot restapi page call - java

I got a simple spring boot application. I am trying load the html file through a rest controller. Below is my folder structure. I am unable to load test.html (just as helloworld code inside it)
#RequestMapping("/show1")
public ModelAndView showpage1() {
System.out.println("## show1");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
return modelAndView;
}
My test.html content
<h1> hello World </h1>

Try doing this :
#RequestMapping("/show1")
public String showpage1() {
return "test";
}
where test.html is your page

You just need to return the string with the name of the view.
#RequestMapping("/showpage")
public String showpage1() {
return "test";
}

Related

i want to know in spring boot web app when we redirect from one jsp to another jsp

As you can see my hellow in request mapping is returning "welcome" jsp page but if I want to use "a href" in welcome jsp page to call view jsp page should I call the controller requestmapping ie "/products" or should I call viewtable jsp page directly?
welcome.jsp
< a href="??"</ahref>
viewtable.jsp
<h1>hellow<h1>
controller
#RequestMapping(value="/hellow",method = RequestMethod.GET) public String
abc(ModelMap model) { return "welcome"; }
#RequestMapping(value="/products", method= RequestMethod.GET)
public String getAllProducts(ModelMap model)
{
System.out.println("in controller");
//return pls.productListAllRecords();
List display;
display=productservice.listAllRecords();
System.out.println(display);
model.addAttribute("records",display);
// return "viewtable";
return "viewtable";
}
If you would like to direct a user to the respective page, you could include a href property within an "< a >" tag with the requestMapping path included.
The following would direct to the above two paths when selected.
Hellow
Products

Is there a way to return HTML page from Restful Controller in Spring Boot?

I am currently making a file upload within my spring boot project. I am using rest controller for my controller as that is what is written within the tutorial that I am using https://www.callicoder.com/spring-boot-file-upload-download-jpa-hibernate-mysql-database-example/
However, I found out that apparently rest controller unable to display HTML page based on what is written here: How to return a html page from a restful controller in spring boot?
Is there a way for displaying my HTML page while retaining the rest controller?
this is my controller
#RestController
public class RekonsiliasiController {
private static final Logger logger = LoggerFactory.getLogger(RekonsiliasiController.class);
#Autowired
private DBFileStorageService dbFileStorageService;
#RequestMapping("/rekonsiliasi")
public String index() {
System.err.println("MASUK PAK EKO OI");
return "rekonsiliasi";
}
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
DBFile dbFile = dbFileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(dbFile.getId())
.toUriString();
return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
file.getContentType(), file.getSize());
}
#GetMapping("/downloadFile/{fileId}")
public ResponseEntity<ByteArrayResource> downloadFile(#PathVariable String fileId) {
// Load file from database
DBFile dbFile = dbFileStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(dbFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
.body(new ByteArrayResource(dbFile.getData()));
}
}
and this is my rekonsiliasi.html
<form method="POST" action="/uploadFile" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
This is what I get currently, a blank page with a simple text
UPDATE
I tried to divide between the index and the file upload to the following.
RekonsiliasiController.java
#Controller
public class RekonsiliasiController {
#RequestMapping("/rekonsiliasi")
public String index() {
System.err.println("MASUK PAK EKO OI");
return "rekonsiliasi";
}
FileController.java
#RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
#Autowired
private DBFileStorageService dbFileStorageService;
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
System.err.println("CEK");
DBFile dbFile = dbFileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(dbFile.getId())
.toUriString();
return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
file.getContentType(), file.getSize());
}
#GetMapping("/downloadFile/{fileId}")
public ResponseEntity<Resource> downloadFile(#PathVariable String fileId) {
// Load file from database
DBFile dbFile = dbFileStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(dbFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
.body(new ByteArrayResource(dbFile.getData()));
}
}
Now the HTML is showing perfectly fine but when I upload the file I got 403 Error. Before I tried to find the problem for this part, I'd like to know whether if there are some ways for displaying my HTML page while retaining the rest controller?
EDIT Delete the 'uploadMultipleFiles' method in FileController.Java and it still gets me 403 error
First of all, in your code in the controller method uploadMultipleFiles, you are actually calling the controller method uploadFile directly by treating it just like another method which is not ideal. The fact that you need to recursively call another controller endpoint means that it is a design flaw in itself. So , try to remove this bit of code by providing the logic in service layer to handle this scenario .
Secondly , splitting the view controller and the rest controller into two separate classes is the right approach. The #RestController annotation is designed to serve json response by default that is why we have the #Controller annotation which serves both model and view. The response code 403 that you receive has nothing to do with this.

I cannot load my templates in the Spring Boot 2

I cannot access the templates I wrote under the templates folder. It will just redirect me to the Whitelabel Error Page. My structure is like this:my controller is under the src/main/java/com.project/controller/IndexController.java while my templates are under the src/main/resources/templates/home.html.My code in the controller is like this:
#Controller
public class IndexController {
#RequestMapping(path = {"/vm"}, method = {RequestMethod.GET})
public String template(Model model) {
return "home";
}
#RequestMapping(path = {"/index"}, method = {RequestMethod.GET})
#ResponseBody
public String index() {
return "Hello world";
}
}
And my home.html is like this:
<html>
<body>
<pre>
Hello World!
</pre>
</body>
</html>
I've solved the problem myself. The thing is the dependency. I did not import the spring-boot-starter-thymeleaf from org.springframework.boot. The dependency is really hard to deal with in Spring.
The default context path of the app would be "/" and there is neither index.html file is present nor a controller method for that path which is why you are seeing that White label Error Page. If you don't want to see that error, add the below property in your application.properties file then you would the HTTP 404 Error.
server.error.whitelabel.enabled=false
For the below method that you have in controller:
Annotation that indicates a method return value should be bound to the web response body.
#RequestMapping(path = {"/vm"}, method = {RequestMethod.GET})
public String template(Model model) {
return "home";
}
Go to http://localhost:8080/vm this would load the home.html file that you have in templates folder.
Whereas for this one:
#RequestMapping(path = {"/index"}, method = {RequestMethod.GET})
#ResponseBody
public String index() {
return "Hello world";
}
You have used the annotation #ResponseBody which would indicate a method that the return value should be bound to the web response body, so you would see the text Hello world in the browser when you hit the http://localhost:8080/index

how to redirect another jsp page in controller using spring MVC?

in WEB-INF having a Jsp File pls see image I am using Spring mvc with Hibernate Database connection,in my controller having data from database in variable val now how can i redirect to another jsp page with data's
Controller Part:
#RequestMapping(value = "/EditShop" , method = RequestMethod.POST)
public String editShop(HttpServletRequest request,HttpServletResponse response) throws IOException
{
String id=request.getParameter("Id");
try
{
String val=shopService1.editShopinfo(id);
System.out.println("Edit Shop : "+val);
}
catch(Exception e)
{
System.out.println("Edit Shop : "+e );
}
return "redirect:/EditShop.jsp";
}
You can pass data from controller to UI(another JSP page) with the help of ModelAndView in Spring.
new ModelAndView("newJSPPage","aliasNameToBean",originalBean);
newJSPPage - replace with the new JSP file which you need to redirect from the controller.
aliasNameToBean - replace with the alias name which you can access bean data at redirected JSP page.
originalBean - replace with the original bean object name which you have the data.
return "redirect:/EditShop.jsp";
Insted of this you have return View Name like
return "EditShop";
In Spring Execution Flow InternalResourceViewResolver will Take Care to Call Jsp.
you have to set val to HttpSession Object like session.setAttribut("val",valueofField);
Then you get that value In your jsp
session.getAttribute("val");
I Hope it helps.

Invoke programmatically JasperReportsPdfView with Spring

I've a Spring project and I'm using Spring MVC + JasperReportsPdfView to export pdf report to my client (JavaFx).
All works fine in the client but I need to get the pdf report also in a custom repository in the server (I want attach the pdf to an automatica email that the server send).
I don't know if this is possibile, and if yes which is the best practice to do that.
This is my controller:
#RequestMapping(value = "/export", method = RequestMethod.POST, params = "tipoReport=2")
public ModelAndView exportFattura(#RequestParam(value = "idFattura", required = true) Long idFattura) throws Exception {
....
....
ModelMap model = new ModelMap();
model.addAttribute("format", "pdf");
return new ModelAndView("fattura", model);
}
and this is the view:
public class FatturaView extends JasperReportsMultiFormatView {
private Logger log = LogManager.getLogger();
#Override
public String getUrl() {
return "classpath:report/Fattura.jasper";
}
}

Categories

Resources