Spring MVC: JSP templates get text after execution

I need to make a specific service call, and I need to pass a String object as a parameter, which is HTML. This HTML is what this service will display (this service sends emails, and this HTML will be the body of the email)

I use JSP files for all templates. All of my views that render an HTML page and return it to users.

I do not know how I can execute the JSP file, fill in all the information and then convert it to text. This is my first experience with Spring MVC.

Edit: related question has really deprecated '09

+4
source share
3 answers

I will focus on the part of converting your jsp to text.
There were some comments about using jsp as a mechanism for creating illustrations, but my suggestion is agnostic for the temple.

The idea is to simulate a browser call, that is, send the form that we want the result to be emailed to, and make sure that we can access this page correctly through the browser.
I assume that the mail request is changing here to get this easily.

public class MailServiceHelper {
    public String getJsp(String url, Map<String,String> form, HttpServletRequest request) {
        //we can figure out the base url from the request
        String baseUrl =""; 
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(baseUrl+"/"+url);
        for (String formElement : form.keySet()) {
            method.setParameter(formElement, form.get(formElement));    
        }

        try {

            int statusCode = client.executeMethod(method);
            if (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES) {
                byte[] responseBody = method.getResponseBody();     
                return new String(responseBody,StandardCharsets.UTF_8);
            }else{
                throw new RuntimeException("Failed to read jsp, server returened with status code: "+statusCode);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to read jsp",e);
        }finally{
            method.releaseConnection();
        }
    }

, .
httpclient 3.1 exanple, . http 3.1, .

HTML : HTML-? , html.

+1

, . , , , Thymeleaf .

, , github, ,

+1

, , request.forward() Mock, , , .

final RequestDispatcher rd = request.getRequestDispatcher("myJsp.jsp");
final MockHttpServletResponse r = new MockHttpServletResponse();
rd.forward(request, r);
final String s = r.getContentAsString();

. MockHttpServletResponse

JSP , , .

0

Source: https://habr.com/ru/post/1612981/


All Articles