Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Polish
Code Block
languagejava
titleSerwlet z adnotacją @Controller
@Controller
@RequestMapping( "/custom" )
public class CustomController
{
	@Autowired
	private PositionService ps;
 
	@RequestMapping( "positions" )
    public @ResponseBody List<User> getPositions( @RequestParam String positionName )
    {
		return ps.getByName(positionName);
	}
}

Po pierwsze dodajemy adnotację @Controller dzięki temu system widzi klasę jako serwlet. Ścieżka do serwletu oznaczonego adnotacją @Controller zaczyna się od api/. Adnotacja @RequestMapping pozwala na zdefiniowanie ścieżki do serwletu. Jak widzimy w przykładzie mamy dwie takie adnotacje, które wraz z przedrostkiem api/ tworzą ścieżkę do serwletu. Dla naszego przykładu ścieżka będzie następująca: api/custom/positions. Dzięki oznaczeniu @ResponseBody odpowiedź serwletu jest automatycznie konwertowana do formatu JSON. Ostatnia adnotacja @RequestParam pozwala na odczytanie parametru przekazanego przez serwlet. Parametr może być również obiektem zakodowanym w JSON, wtedy system automatycznie go zdekoduje.

Metody żądania

Definiowanie metody żądania odbywa się za pomocą adnotacji @RequestMapping( method = "method" ).

Podstawowe metody są następujące:

  • RequestMethod.GET
  • RequestMethod.POST
  • RequestMethod.DELETE

Dla powyższego przykładu pobranie pozycji za pomocą metody GET będzie wyglądać następująco:

Code Block
languagejava
@RequestMapping( value = "positions", method = RequestMethod.GET )
public @ResponseBody List<User> getPositions( @RequestParam String positionName )
{
    return ps.getByName(positionName);
}

Przekazywanie parametrów w linku

Code Block
languagejava
@RequestMapping( value = "positions/{positionName}", method = RequestMethod.GET )
public @ResponseBody List<User> getPositions( @PathVariable String positionName )
{
    return ps.getByName(positionName);
}

Istnieje możliwość przesyłania podstawowych parametrów w linku RESTowym żądania. Zmienną taką należy umieścić w klamrach {}, a następnie przekazać ją do metody za pomocą odczytania parametru

@PathVariable String positionName. Teraz jeżeli wywołamy url: api/custom/positions/test, to jako parametr positionName zostanie do matody przekazana wartość test.

 

Przydatne zasoby:

Pobieranie pliku

Klasa com.suncode.pwfl.web.support.io.DownloadResource ułatwia stworzenie serwletu do pobierania pliku, dbając o ustawienie odpowiednich nagłówków odpowiedzi HTTP:

  • Content-Disposition - nagłówek zawierający nazwę pliku (nazwa pliku może zawierać również znaki UTF-8)
  • Content-Type - typ pliku odczytany z rozszerzenia za pomocą JAF (JavaBeans Activation Framework)
  • Content-Length - rozmiar pliku

 

W tym celu należy z dowolnej metody kontrolera Spring MVC (@Controller) zwrócić odpowiedni obiekt klasy DownloadResource. Zasób ten zostanie automatycznie przekazany do przeglądarki z odpowiednimi nagłówkami. Należy pamiętać o adnotacji @ResponseBody która musi być obecna na metodzie.

Poniżej znajduje się przykład takiego kontrolera wraz z przykładową odpowiedzią serwera.

Code Block
languagejava
@Controller
@RequestMapping("/file")
public class DownloadFileServlet()
{
	@RequestMapping( value = "download/{filePath}", method = RequestMethod.GET )
    public @ResponseBody DownloadResource download( @PathVariable String filePath )
        throws Exception
    {
        File file = new File(filePath);
        return new DownloadResource( file );
    }
}
NagłówekWartość
Content-Disposition
attachment; filename="Faktury_ca%C5%82o%C5%9B%C4%87.pdf"; filename*=UTF-8''Faktury_ca%C5%82o%C5%9B%C4%87.pdf
Content-Length
15913
Content-Type
application/pdf;charset=UTF-8
English
Code Block
languagejava
titleServlet with @Controller annotation
@Controller
@RequestMapping( "/custom" )
public class CustomController
{
	@Autowired
	private PositionService ps;
 
	@RequestMapping( "positions" )
    public @ResponseBody List<User> getPositions( @RequestParam String positionName )
    {
		return ps.getByName(positionName);
	}
}

First, add the @Controller so the system sees the class as a servlet. The path to a servlet annotated with the @Controller starts with api/. The @RequestMapping annotation allows us to define the path to the servlet. As you can see in the example you have two such annotations, which together with the prefix api/ form the path to the servlet.

For example, the path would be: api/custom/positions. With the @ResponseBody annotation, the servlet's response is automatically converted to JSON format. The last @RequestParam annotation allows you to read the parameter passed by the servlet. The parameter can also be a JSON-encoded object, in which case the system will automatically decode it.

Request methods

Defining a request method is done with the @RequestMapping( method = "method" ) annotation.

The basic methods are as follows:

  • RequestMethod.GET
  • RequestMethod.POST
  • RequestMethod.DELETE

For the above example, retrieving the item using the GET method will look like this:

Code Block
languagejava
@RequestMapping( value = "positions", method = RequestMethod.GET )
public @ResponseBody List<User> getPositions( @RequestParam String positionName )
{
    return ps.getByName(positionName);
}
Code Block
languagejava
@RequestMapping( value = "positions/{positionName}", method = RequestMethod.GET )
public @ResponseBody List<User> getPositions( @PathVariable String positionName )
{
    return ps.getByName(positionName);
}

It is possible to send basic parameters in the REST link of the request. Such a variable should be placed in {} brackets, and then transferred to the method by reading the parameter

@PathVariable String positionName. Now if we call url: api/custom/positions/test, the value test will be passed to the matoda as the positionName parameter.

 

Useful resources:

File download

The com.suncode.pwfl.web.support.io.DownloadResource class simplifies the creation of a servlet to download a file by taking care of setting the appropriate HTTP response headers:

  • Content-Disposition - a header containing the file name (the file name can also contain UTF-8 characters)
  • Content-Type - a header containing the file name (the file name can also contain UTF-8 characters)
  • Content-Length - the size of the file

To do this, return the appropriate DownloadResource class object from any Spring MVC controller method (@Controller). This resource will be automatically passed to the browser with the appropriate headers. Note the @ResponseBody annotation which must be present on the method.

Below is an example of such a controller along with a sample server response.

Code Block
languagejava
@Controller
@RequestMapping("/file")
public class DownloadFileServlet()
{
	@RequestMapping( value = "download/{filePath}", method = RequestMethod.GET )
    public @ResponseBody DownloadResource download( @PathVariable String filePath )
        throws Exception
    {
        File file = new File(filePath);
        return new DownloadResource( file );
    }
}
HeaderValue
Content-Disposition
attachment; filename="Faktury_ca%C5%82o%C5%9B%C4%87.pdf"; filename*=UTF-8''Faktury_ca%C5%82o%C5%9B%C4%87.pdf
Content-Length
15913
Content-Type
application/pdf;charset=UTF-8