SO question 2370960

Блог

Как вернуть HTML-страницу из RestController весной?

#java #html #spring #spring-boot #rest

Вопрос:

Я изучаю веб-сервисы Spring и Rest, так что это немного сбивает меня с толку. Это мой класс:

 RestController @RequestMapping("/app-api/users") public class UserApiController < @Autowired UserRepository userRepo; @GetMapping public IterablegetUsers() < return userRepo.findAll(); >> 

Теперь, когда я тестирую этот GET запрос в каком-либо клиенте rest, я получаю HTTP status 200 и всех пользователей в JSON формате. Но как я могу их отобразить HTML ? Я попробовал это как обычный контроллер:

 @GetMapping("/test") public String getUsers(Model model) < Iterableusers = userRepo.findAll(); model.addAttribute("users", users); return "test-user"; > 

Но это не работает, так как он просто возвращается test-user в виде обычного текста. Мой вопрос в том, каков правильный способ и соглашение для обработки данных RestController и их отображения в html?

Комментарии:

1. Вам нужно будет вернуть полный HTML-документ и установить тип носителя в text/html ( @GetMapping(«/test», produces = javax.ws.rs.core.MediaType.TEXT_HTML) )

2. @Turing85 я получаю ошибку 404.

3. Передаете ли вы правильные параметры методу getUsers(режим модели)? Вы обращаетесь к правильному URL-адресу(app-api/пользователи/тест)? Вы столкнулись с ошибкой 404 в браузере или restclient?

Ответ №1:

Веб-службы Spring обычно используются для представления API, предоставляющего необработанные данные для использования автономными приложениями (например, angular, мобильным приложением), поначалу это может сбить с толку.

Если вы хотите, чтобы ваше приложение предоставляло HTML-страницу, я рекомендую вам взглянуть на ThymeLeaf, я думаю, есть и другие способы сделать то же самое, но это единственный, который я знаю. Надеюсь, это поможет, хорошего дня !

Комментарии:

1. У меня есть Thymeleaf в моем проекте, но я все еще получаю ошибку. Что мне делать?

Ответ №2:

 @GetMapping("/test") public String getUsers(Model model)

следует перейти в @Controller аннотированный класс (не @RestController).

 @GetMapping public Iterable getUsers()

в другой @RestController класс.

Это два разных подхода.
Вы используете @Controller для формирования HTML-страницы на стороне сервера с помощью одного из движков шаблонов (например, упомянутого Thymeleaf).
В то время как @RestController предназначен для конечной точки API. Обычно вы используете javascript для выполнения запроса ajax и формирования HTML на стороне клиента.

Комментарии:

1. Спасибо за ответ, так ли разработчики обычно обращаются с контроллерами rest? Чтобы сформировать HTML-страницу, мы должны сделать ajax-запрос на стороне клиента?

2. Контроллеры Rest предназначены для API, где P означает программирование. Вам нужна какая-то программа для запроса контроллеров rest. Это может быть javascript ajax (обычно для создания html) или любая другая программа. Вы можете использовать один из двух подходов или смесь обоих. Использование контроллеров rest и некоторых библиотек/фреймворков js, таких как React.js это более продвинутая техника, но для простых вещей можно использовать обычные контроллеры и рендеринг на стороне сервера.

Источник

Читайте также:  Mod в питоне примеры

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the $<> things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

@WebServlet("/hello") public class HelloWorldServlet extends HttpServlet < @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String message = "Hello World"; request.setAttribute("message", message); // This will be available as $request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response); > > 

And /WEB-INF/hello.jsp look like:

     

Message: $

When opening http://localhost:8080/contextpath/hello this will show

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the «Frequent» tab of all questions tagged [servlets] to find frequently asked questions.

Источник

How to return an html document from java servlet? [duplicate]

Sorry for being noob! EDIT: I already have the html in separate documents. So I need to either return the document, or read/parse it somehow, so I’m not just retyping all the html. EDIT: I have this in my web.xml

 Monkey com.self.edu.MonkeyServlet  Monkey /monkey  

1 Answer 1

You either print out the HTML from the Servlet itself (deprecated)

PrintWriter out = response.getWriter(); out.println(""); out.println("

My HTML Body

"); out.println("");

or, dispatch to an existing resource (servlet, jsp etc.) (called forwarding to a view) (preferred)

RequestDispatcher view = request.getRequestDispatcher("html/mypage.html"); view.forward(request, response); 

The existing resource that you need your current HTTP request to get forwarded to does not need to be special in any way i.e. it’s written just like any other Servlet or JSP; the container handles the forwarding part seamlessly.

Just make sure you provide the correct path to the resource. For example, for a servlet the RequestDispatcher would need the correct URL pattern (as specified in your web.xml)

RequestDispatcher view = request.getRequestDispatcher("/url/pattern/of/servlet"); 

Also, note that the a RequestDispatcher can be retrieved from both ServletRequest and ServletContext with the difference that the former can take a relative path as well.

Sample Code

public class BlotServlet extends HttpServlet < public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException < // we do not set content type, headers, cookies etc. // resp.setContentType("text/html"); // while redirecting as // it would most likely result in an IllegalStateException // "/" is relative to the context root (your web-app name) RequestDispatcher view = req.getRequestDispatcher("/path/to/file.html"); // don't add your web-app name to the path view.forward(req, resp); >> 

Источник

How to return actual html file using JAX-RS

You can just return an instance of java.io.InputStream or java.io.Reader — JAX-RS will do the right thing.

@GET @Produces() public InputStream viewHome()

hmm, good suggestion sir. I’m getting filenotfoundexception -_- Does it search the «tosearch.txt» relative to the calling file?

That depends what the «current directory» of your application is — which depends on where the app is executed from, i.e. it can (and probably will) change at runtime. System.out.println(System.getProperty(«user.dir»)); will print the path that relative files are resolved from.

If you’re in a Servlet application, the getResourceAsStream() method (docs.oracle.com/javaee/6/api/javax/servlet/…) is a better option then using a java.io.File instance.

@Alex if it’s a file in the web application itself (that is, under src/main/wwwroot as opposed to in the servlet app’s classpath), then calling getResourceAsStream on the ServletContext is the way forward: docs.oracle.com/javaee/7/api/javax/servlet/…

This is my preferred way of serving a web page using JAX-RS. The resources for the web page (html, css, images, js, etc.) are placed in main/java/resources , which should deploy them in WEB-INF/classes (may require some configuration depending on how you set up your project). Inject ServletContext into your service and use it to find the file and return it as an InputStream . I’ve included a full example below for reference.

@Path("/home") public class HomeService < @Context ServletContext servletContext; @Path("/") @GET public InputStream getFile(@PathParam("path") String path) < try < String base = servletContext.getRealPath("/WEB-INF/classes/files"); File f = new File(String.format("%s/%s", base, path)); return new FileInputStream(f); >catch (FileNotFoundException e) < // log the error? return null; >> > 

Источник

How to return an HTML page from a RESTful controller in Spring Boot?

I want to return a simple HTML page from a controller, but I get only the name of the file not its content. Why?

This is my controller code:

@RestController public class HomeController < @RequestMapping("/") public String welcome() < return "login"; >> 

This is my project structure:

enter image description here

[

try to add a servlet to direct to index.html @ServletComponentScan then add @WebSevlet(urlPatterns = «») MainIndex

21 Answers 21

When using @RestController like this:

@RestController public class HomeController < @RequestMapping("/") public String welcome() < return "login"; >> 

This is the same as you do like this in a normal controller:

@Controller public class HomeController < @RequestMapping("/") @ResponseBody public String welcome() < return "login"; >> 

Using @ResponseBody returns return «login»; as a String object. Any object you return will be attached as payload in the HTTP body as JSON.

This is why you are getting just login in the response.

@Itération122442 You should use Controller annotation for the class and you should remove the ResponseBody annotation from method named welcome()

lol i do not get why this is marked as correct, it does not tell the answer it just explains the problem

  1. Must put the html files in resources/templates/
  2. Replace the @RestController with @Controller
  3. Remove if you are using any view resolvers.
  4. Your controller method should return file name of view without extension like return «index»
  5. Include the below dependencies:
 org.springframework.boot spring-boot-starter-web  org.springframework.boot spring-boot-starter-thymeleaf  org.springframework.boot spring-boot-devtools ` 

With just spring-starter-web dependency I was able to serve html pages located inside src/main/resources/static , by typing localhost: 8080/helloworld.html( the entire name). But using thmleaf it automatically maps to the html files. SO MY QUESTION is there any option to serve the files through rest end points by just including spring-starter-web dependency

You can try using ModelAndView :

@RequestMapping("/") public ModelAndView index ()

@kukkuz pretty much answered to the question ‘why?’. For those who are still looking into ‘how’, accumulating what others have answered.

@RestController public class MyRestController < @RequestMapping("/") public ModelAndView welcome() < ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("login.html"); return modelAndView; >> 
  • pay attention that view name is: ‘login.html’ (full file name).
  • also it is important where the file is located, by default login.html must be in resources/static or resources/public

You may set up an application parameter for a default suffix like:

in this case view name must be without extension like ‘login’.

Some suggested thymeleaf can be used. means you have in your pom.xml dependencies something like this:

 org.springframework.boot spring-boot-starter-thymeleaf 2.4.4  

In that scenario login.html by default must sit in: resources/templates folder, and the call is similar only difference now is in a view name, since .html is used by tymeleaf as a default value.

// fails by default // NO fail if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html // NO fail if thymeleaf is added, and there is a file login.html in a resources/templates folder. @RequestMapping("/loginTest") public ModelAndView loginTest ()
@Controller public class MyController < //gets html from a default 'resources/public' or 'resources/static' folder @RequestMapping(path="/welcome") public String getWelcomePage()< return "login.html"; >//gets html from a default 'resources/public' or 'resources/static' folder @RequestMapping("/welcome1") public ModelAndView getWelcomePageAsModel() < ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("login.html"); return modelAndView; >// fails with 404 resource not found by default // NO fail, if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html // NO fail, if thymeleaf is added, and there is a file login.html in a resources/templates folder @RequestMapping(path="/welcome2") public String thisFails() < return "login"; >> 

Источник

Оцените статью