I'm working with a project that has the back in Java deployed at Heroku and the front in Angular dpeloyed at Firebase. Data base is in CleverCloud.
I'm having problems with bringing data to the front from the data base.
PERSON TABLE (WORKS JUST FINE):
CONTROLLER (JAVA):
package com.portfoliocardone.portfoliocardone.Controller;
import com.portfoliocardone.portfoliocardone.Entity.Person;
import com.portfoliocardone.portfoliocardone.Interface.IPersonService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin(origins = "https://portfoliocardone.web.app")
public class PersonController {
#Autowired IPersonService ipersonService;
#GetMapping("/person/get")
public List<Person> getPerson(){
return ipersonService.getPerson();
}
#PostMapping("/person/new")
public String createPerson(#RequestBody Person person){
ipersonService.savePerson(person);
return "The person was created correctly";
}
#DeleteMapping("/person/delete/{id}")
public String deletePerson(#PathVariable Long id){
ipersonService.deletePerson(id);
return "The person was deleted correctly";
}
//URL:PORT/person/edit/id/name & lastname & img & about me
#PutMapping("/person/edit/{id}")
public Person editPerson(#PathVariable Long id,
#RequestParam("name") String newName,
#RequestParam("lastname") String newLastname,
#RequestParam("img") String newImg,
#RequestParam("aboutme") String newAboutme){
Person person = ipersonService.findPerson(id);
person.setName(newName);
person.setLastname(newLastname);
person.setImg(newImg);
person.setAboutme(newAboutme);
ipersonService.savePerson(person);
return person;
}
#GetMapping("/person/find/profile")
public Person findPerson(){
return ipersonService.findPerson((long)1);
}
}
SERVICE ANGULAR PROJECT:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { person } from '../model/person.model';
#Injectable({
providedIn: 'root'
})
export class PersonService {
URL = 'https://portfoliocardone.herokuapp.com/person/';
constructor(private http:HttpClient) { }
public getPerson(): Observable<person>{
return this.http.get<person>(this.URL+'find/profile');
}
}
After I bring the data to the component by putting {{person.name}}, {{person.lastname}}, {{person.aboutme}} in the html file. I left the image empty and it works just fine.
HERE IS THE PROBLEM WITH THE OTHER TABLE:
CONTROLLER (JAVA):
package com.portfoliocardone.portfoliocardone.Controller;
import com.portfoliocardone.portfoliocardone.Entity.Experience;
import com.portfoliocardone.portfoliocardone.Interface.IExperienceService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin(origins = "https://portfoliocardone.web.app")
public class ExperienceController {
#Autowired IExperienceService iexperienceService;
#GetMapping("/experience/get")
public List<Experience> getExperience(){
return iexperienceService.getExperience();
}
#PostMapping("/experience/new")
public String createExperience(#RequestBody Experience experience){
iexperienceService.saveExperience(experience);
return "The experience was created correctly";
}
#DeleteMapping("/experience/delete/{id}")
public String deleteExperience(#PathVariable Long id){
iexperienceService.deleteExperience(id);
return "The experience was deleted correctly";
}
//URL:PORT/experience/edit/id/title & time & location & description
#PutMapping("/experience/edit/{id}")
public Experience editExperience(#PathVariable Long id,
#RequestParam("title") String newTitle,
#RequestParam("time") String newTime,
#RequestParam("location") String newLocation,
#RequestParam("description") String newDescription){
Experience experience = iexperienceService.findExperience(id);
experience.setTitle(newTitle);
experience.setTime(newTime);
experience.setLocation(newLocation);
experience.setDescription(newDescription);
iexperienceService.saveExperience(experience);
return experience;
}
#GetMapping("/experience/find/profile/{id}")
public Experience findExperience(#PathVariable("id") Long id){
return iexperienceService.findExperience((long)id);
}
}
ANGULAR SERVICE
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { experience } from '../model/experience.model';
#Injectable({
providedIn: 'root'
})
export class ExperienceService {
URL = 'https://portfoliocardone.herokuapp.com/experience/';
constructor(private http:HttpClient) { }
public getExperience(): Observable<experience>{
return this.http.get<experience>(this.URL+'find/profile/{id}');
}
}
ERRORS I GET IN CONSOLE:
headers: An, status: 400, statusText: 'OK', url:...
Does someone know how to be able to bring the data from this second table? Thanks!
Related
Hi I am new to spring and have created an Export csv application with two controllers which can give all the data as well as selective columns data and want to write junits for the same but it is quite difficult for me to do the same as I am not aware how i should do it some help would be really great
Main class:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
import net.bytebuddy.implementation.bind.annotation.Super;
#SpringBootApplication
public class ExampleApplication implements CommandLineRunner {
#Autowired
ExampleRepository exampleRepository;
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Example> example= new ArrayList<>();
// create dummy
example.add(new Example(1,"abc","sachin","abc","abc"));
example.add(new Example(2,"abc","rahul","abc","abc"));
example.add(new Example(3,"abc","rahul","abc","abc"));
exampleRepository.saveAll(example);
}
}
Entity layer:
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="example")
public class Example{
#Column(name="city")
private String city;
#Column(name="name")
private String name;
#Column(name="amount")
private String amount;
#Column(name="country")
private String country;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
//getter and setters
}
Repository layer is as follows:
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.model.Example;
#Repository("exampleRepository")
public interface ExampleRepository extends JpaRepository<Example,Long> {
List<Report> findByName(String name);
}
service layer is as follows
package com.example.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
#Transactional
#Service
public class ExampleService {
#Autowired
ExampleRepository exampleRepository;
public List<Example> fetchAll() {
return exampleRepository.findAll();
}
public List<Example> findByName(String name){
return exampleRepository.findByName(name);
}
}
I have 2 controllers one to get all details and one to get selective columns and here we are generating csv files based on records that match the name
COntroller 1:
package com.example.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/demo")
public class Controller1 {
#Autowired
ExampleService exampleService;
#GetMapping("/result")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "names.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(examplesService.findByName(name));
}
}
Controller 2:
package com.reports.controllers;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/example")
public class Controller2 {
#Autowired
ExampleService exampleService;
#GetMapping("/output")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Example.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())
))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(exampleService.findByname(name));
}
}
Try this approach :
generate a file in your /src/test/resources path and then test if it contains the generated data you expected
use combine it with a file system mocking to do it
You will :
test your ResController
mock your Service class
Also use Contructor Injection for you dependency
I have a HTML page that is launched from a java controller after a post and I want to attach a query string value in the url ex: (localhost:8000/gdata?id=11). Can this be done? Here is my controller code:
package com.sa.example;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestParam;
import com.sentinel.advisor.GData;
import com.sentinel.advisor.GDataJdbcRepository;
#Controller
public class GDataController {
#Autowired
GDataJdbcRepository repository;
#GetMapping("/gdata")
public String gDataForm(Model model) {
return "gData";
}
#PostMapping("/gdata")
public String gDataSubmit(#ModelAttribute GData gData) {
String returnString = repository.insert(gData);
//returnString should be returned in the url as a query string
return "result";
}
}
You can use a redirect (it is best practice to redirect after post regardless see - https://en.wikipedia.org/wiki/Post/Redirect/Get.
Spring's redirect view:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/view/RedirectView.html
Something like:
#Controller
public class GDataController {
#Autowired
GDataJdbcRepository repository;
#GetMapping("/gdata")
public String gDataForm(Model model) {
return "gData";
}
#PostMapping("/gdata")
public RedirectView gDataSubmit(#ModelAttribute GData gData) {
String returnString = repository.insert(gData);
return new RedirectView("/sucess?returnString=" + returnString, true);
}
#GetMapping("/success")
public String getResultPage(#RequestParam("returnString")String returnString){
return "result";
}
}
I have an application with two packages. In the first package, I have 2 controllers. The first controller is called APIController.java which displays a view. This is the code of the controller:
package com.dogo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping()
public class APIController {
#RequestMapping("/api")
public String apiChat() {
return "apiChat.html";
}
}
The second controller is called HomeController.java which I use to display the index.html page. This is the code:
package com.dogo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String index() {
return "index.html";
}
}
The second package also contains a controller called MessageController.java. This is used to update a dao database based on the parameters passed in the url. This is the code for this controller:
package com.dogo.chat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping()
public class MessageController {
#Autowired
MessageRepository dao;
#GetMapping("/chat")
public List<Message> getMessages(){
List<Message> foundMessages = dao.findAll();
return foundMessages;
}
#PostMapping("/chat")
public ResponseEntity<Message> postMessage(#RequestBody Message message)
{
// Saving to DB using an instance of the repo Interface.
Message createdMessage = dao.save(message);
// RespEntity crafts response to include correct status codes.
return ResponseEntity.ok(createdMessage);
}
#GetMapping("/chat/{id}")
public ResponseEntity<Message> getMessage(#PathVariable(value="id")
Integer id){
Message foundMessage = dao.findOne(id);
if(foundMessage == null) {
return ResponseEntity.notFound().header("Message","Nothing found with that id").build();
}
return ResponseEntity.ok(foundMessage);
}
#DeleteMapping("/message/{id}")
public ResponseEntity<Message> deleteMessage(#PathVariable(value="id") Integer id){
Message foundMessage = dao.findOne(id);
if(foundMessage == null) {
return ResponseEntity.notFound().header("Message","Nothing found with that id").build();
}else {
dao.delete(foundMessage);
}
return ResponseEntity.ok().build();
}
}
When I type http://localhost:8080/api into my browser, the apiChat.html page is displayed. When I change the #RequestMapping() in APIController.java to #RequestMapping("/api") and I type http://localhost:8080/api/api I get a 404 error. I had expected the apiChat.html page to be displayed. What am I missing? Thank you.
Im trying to have java respond to a GET request from Postman. When I use Postman to send a GET request to localhost:8080/chat this is the response (I had expected to get an empty list returned as there is no data present yet:
{
"timestamp": "2018-04-02T20:00:26.413+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/chat"
}
I have 2 packages in my application. They are com.dogo and com.dogochat.chat. The file in com.dogo is DogoApplication.java. This is the code:
package com.dogo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DogoApplication {
public static void main(String[] args) {
SpringApplication.run(DogoApplication.class, args);
}
}
The second package is called com.dogochat.chat. There are 3 files (2 classes and 1 interface). The file names are Message.java, MessageController.java, and MessageRepository.java.
This is the code in Message.java:
package com.dogochat.chat;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="message")
public class Message {
#Id
#GeneratedValue
private Integer id;
private String name;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
This is the code in MessageController.java:
package com.dogochat.chat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/chat")
public class MessageController {
#Autowired
MessageRepository dao;
#GetMapping("/get")
public List<Message> getMessages(){
List<Message> foundMessages = dao.findAll();
return foundMessages;
}
#PostMapping("/post")
public ResponseEntity<Message> postMessage(#RequestBody Message message)
{
// saving to DB using instance of the repo interface
Message createdMessage = dao.save(message);
// RespEntity crafts response to include correct status codes.
return ResponseEntity.ok(createdMessage);
}
}
This is the code in MessageRepository.java (although I dont think this is needed for this small test)
package com.dogochat.chat;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MessageRepository extends JpaRepository<Message, Integer>{
}
Any help/suggestions are greatly appreciated.
Thanks.
I know I am pretty late for the response, but better late than never.
This is a very common mistake for new Spring boot developers and I have also faced this issue several times.
The reason for this is the package under which you have your main() method.
In your case your MessageController, Message and your MessageRepository is under the package com.dogochat.chat, but then your main() method is under com.dogo which is completely a different package.
#SpringBootApplication internally runs #ComponentScan and if parent package and child packages are different, it cannot run and scan and throws the above error.
To avoid this confusion, follow this package structure.
Hope this helps. Happy coding !
Check to see if your #SpringBootApplication class is on top of all your packages or at least in the same package. It seems like your URL path is not visible.
Also, in your PostMan, you have to configure your headers the content-type=application/json.
For a more readable code (just my point of view), you should have something like this :
package com.dogochat.chat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/chat")
public class MessageController {
#Autowired
MessageRepository dao;
#GetMapping("/get")
public List<Message> getMessages(){
List<Message> foundMessages = dao.findAll();
return foundMessages;
}
#PostMapping("/post")
public ResponseEntity<Message> postMessage(#RequestBody Message message)
{
// saving to DB using instance of the repo interface
Message createdMessage = dao.save(message);
// RespEntity crafts response to include correct status codes.
return ResponseEntity.ok(createdMessage);
}
}
I have a simple PersonController class that provides save() method to persist the object from http post request.
package org.rw.controller;
import java.sql.Timestamp;
import java.util.List;
import org.rw.entity.Person;
import org.rw.service.PersonService;
import org.rw.spring.propertyeditor.TimestampPropertyEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value="/person")
public class PersonController {
private static final Logger logger = LoggerFactory.getLogger(PersonController.class);
#Autowired
private PersonService personService;
#Autowired
TimestampPropertyEditor timestampPropertyEditor;
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Timestamp.class, "dob", timestampPropertyEditor);
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public String save(Model model, Person person) {
Long personId = personService.save(person);
return "redirect:view/" + personId;
}
}
As the save() method returns as return "redirect:view/" + personId;. It will be diffrerent for every request. it may be like "view/5" or "view/6" depending on the id of the object that has been persisted.
Then i have a simple class to test the above controller with spring mocking.
package org.rw.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.rw.service.UserService;
import org.rw.test.SpringControllerTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
public class PersonControllerTest extends SpringControllerTest {
#Autowired
private UserService userService;
#Test
public void add() throws Exception {
mockMvc.perform(get("/person/add", new Object[0])).andExpect(status().isOk());
}
#Test
public void save() throws Exception {
UserDetails userDetails = userService.findByUsername("anil");
Authentication authToken = new UsernamePasswordAuthenticationToken (userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
mockMvc.perform(
post("/person/save", new Object[0])
.param("firstName", "JunitFN")
.param("lastName", "JunitLN")
.param("gender", "M")
.param("dob", "11/02/1989")
).andExpect(
redirectedUrl("view")
);
}
}
now here i have a problem that redirectedUrl("view") is rejecting value "view/5". I have tried redirectedUrl("view*") and redirectedUrl("view/*") but its not working.
Edit :
Here I have got a workaround as per below
MvcResult result = mockMvc.perform(
post("/person/save", new Object[0])
.param("firstName", "JunitFN")
.param("lastName", "JunitLN")
.param("gender", "MALE")
.param("dob", "11/02/1989")
).andExpect(
//redirectedUrl("view")
status().isMovedTemporarily()
).andReturn();
MockHttpServletResponse response = result.getResponse();
String location = response.getHeader("Location");
Pattern pattern = Pattern.compile("\\Aview/[0-9]+\\z");
assertTrue(pattern.matcher(location).find());
but still i am looking for the proper way.
update:
I have posted the same issue on spring jira here :
Since spring 4.0 you can use redirectedUrlPattern as pointed by Paulius Matulionis
As of spring 3.x this is not supported out of the box but you can easily add you custom result matcher
private static ResultMatcher redirectedUrlPattern(final String expectedUrlPattern) {
return new ResultMatcher() {
public void match(MvcResult result) {
Pattern pattern = Pattern.compile("\\A" + expectedUrlPattern + "\\z");
assertTrue(pattern.matcher(result.getResponse().getRedirectedUrl()).find());
}
};
}
And use it like build-in matcher
mockMvc.perform(
post("/person/save", new Object[0])
.param("firstName", "JunitFN")
.param("lastName", "JunitLN")
.param("gender", "M")
.param("dob", "11/02/1989")
).andExpect(
redirectedUrlPattern("view/[0-9]+")
);
Since 4.0 it is available in Spring itself.
Please check here.