Return value in Spring boot framework - spring-mvc

I have a project using spring boot framework. From what I understand of the current code base the API's are designed in a way to work with the web browser. For Example
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(#ModelAttribute("userForm") User userForm, Model model, RedirectAttributes redirectAttributes){
// Login code
return "redirect:/home"
}
Is it possible to modify this code base to that we return a JSON instead of the redirection? My ultimate goal is to send have a mobile application making the requestion to this endpoint. Is it possible to modify this code base or I have to create a new endpoint for mobile application.
Please excuse me if this sounds like a stupid question. I have no prior experience with spring boot and trying to understand my options
Thank You.

Related

.Net Framework C# Web API HttpGet complex object

Good evening,
I have one scenario that i have a httpGet method with complex object and needs to call this from another .net project by passing Json object., Below is the sample.
APIController
[HttpGet]
[Route("GetName")]
public async Task<string> GetName([FromUri]MyClass myClass)
{
return myClass?.MyName?.ToString() + "this is my method result";
}
Postman
http://localhost/api/NameSearch/GetName?MyClass={'MyName':'TestName'}
I know this is very easy to achieve if i change the action from httpGet to httpPost., But this has been told that i am not doing any update within my api, so i should not use the Post. Also i should not be sending this as individual parameter like ?MyName=''&MySecondParam='',etc., The request has to be passed as single Json object to the API.
Please kindly suggest if there is any option. I tried the above ?MyClass={'MyName':'TestName'} which is not working.
Thanks in advance.

Spring MVC - log every incoming http request call with payload into database

experts, I would log every incoming http request call with payload into database.
I checked there would be 2 approaches.
use filter or interceptor.
I feel filter is so easier for me to implement.
what would be best approach for my purpose?
please kindly advise.
thank you very much!
if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.
But anyway, just do the way which make you feel easily and simply.
Note:
Interceptor work in spring application context
Servlet work in web context
Use Spring AOP. Use any advice according to your needs.
#Aspect
#Component
public class Test {
#Around("#annotation(mapping) ")
public Object preAuthUserPersmission(ProceedingJoinPoint joinPoint, RequestMapping mapping) throws Throwable {
Object[] parameters = joinPoint.getArgs();
// Your actions on the input parameters
return joinPoint.proceed(joinPoint.getArgs());
}
}

Using reserved word "action" as an MVC parameter name

To provide details regarding my platform. I am using Visual Studio 2017 with a .NET Core Web project.
I am implementing a new back-end for a client for which I cannot alter the client. I am attempting to use MVC to accomplish this.
The URL which I must be able to respond to is -> https://my.server.com:8443/portal/gateway?sessionId=0A6405100000001D04FB55FE&portal=4ba457d0-e371-11e6-92ce-005056873bd0&action=cwa&token=3fcbc246bb3c35a5fa8055fec6bbf431
I would like to extract the values for :
sessionId
portal
action
token
As they all have meaning.
I have created a new view folder within my project called "Portal" and have created a new MVC controller named "PortalController".
I have created a new View called gateway.cshtml and also have implemented the following function ->
public IActionResult Gateway(string sessionId, string portal, string action, string token)
{
ViewData["Message"] = "Gateway";
return View();
}
When I set a breakpoint within the function, I receive the following values for the URL provided above ->
sessionId "0A6405100000001D04FB55FE" string
portal "4ba457d0-e371-11e6-92ce-005056873bd0" string
action "gateway" string
token "3fcbc246bb3c35a5fa8055fec6bbf431" string
As can be seen in the output of the debugger, for the parameter named "action", isntead of receiving the value "cwa" as passed by the client, I instead receive the name "gateway" which is passed by MVC as the name of the action.
Is there a "proper way" of handling this?
I would prefer to avoid altering the routes within the startup.cs file as this hurts the modularity of the code. I would welcome attributes that could be used to reroute the parameter names.
Another alternative I could see (buy can't figure out) is to simply make use of the HTTP request to read the values I'm interested in instead of using function parameters.
Thank you very much in advance for any assistance you can provide!
In .Net Core you can get your action parameter value straight off the Request with
var action= Request.Query["action"];
where in .Net Framework it was
var action= Request.QueryString["action"];

What's wrong with my spring-social ConnectController?

I'm trying to make a Spring Boot app that will connect to Fitbit's api using spring-social. I've (half-way) implemented a ConnectionFactory and it's dependencies for Fitbit, and am trying to consume it from my app. Part of this involves starting up a ConnectController to handle the OAuth2 "dance".
When I try to hit the ConnectController through my browser at http://localhost:8080/connect or http://localhost:8080/connect/fitbit I get redirected to the whitelable error page with the message:
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
I don't really understand what I'm seeing, but when I set DEBUG level logging and use some breakpoints it looks like hitting /connect from the browser results in Spring trying to find something called connect/status and hitting /connect/fitbit result in spring trying to find something named /connect/fitbitConnect and then trying to internally make a GET request to /connect/connect/fitbitConnect.
In both cases it looks like the methods on ConnectController corresponding to /connect and /connect/{providerId} get called fine, and then Spring bombs when it goes looking for all that other stuff.
Here is the SocialConfigurer implementation I'm using which creates the ConnectController bean:
#Configuration
#EnableSocial
#PropertySource("${properties.path}/fitbot-service.properties")
public class SpringSocialConfig implements SocialConfigurer{
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment) {
connectionFactoryConfigurer.addConnectionFactory(new FitbitConnectionFactory(
environment.getProperty("fitbit.clientId"),
environment.getProperty("fitbit.clientSecret")
));
}
#Override
public UserIdSource getUserIdSource() {
return new SessionUserIdSource();
}
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new InMemoryUsersConnectionRepository(connectionFactoryLocator);
}
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
return new ConnectController(connectionFactoryLocator, connectionRepository);
}
}
What on earth is going on here? What am I doing wrong?
I believe this to be related to your question regarding GET vs. POST in ConnectController, so you may have already answered this for yourself. Nonetheless, let me clarify why it's looking for connect/status and connect/fitbitConnect.
Those are view names. When you do a GET for /connect, you're asking ConnectController to fetch connection status for all providers and to place it in the model, after which it will forward that model to a view whose logical name is "connect/status". Usually this is a JSP at the path "/connect/status.jsp" or maybe a Thymeleaf template at "/connect/status.html", but it can be any view following the rules of whatever Spring MVC view resolvers are in play.
Likewise, a GET request for /connect/fitbit is asking ConnectController to fetch connection status for the "fitbit" provider and to place that information in the model and forward it on to a view whose name is "/connect/fitbitConnect" (if there isn't a connection) or "/connect/fitbitConnected" (if there is a connection).
Aside from answering your question, may I also request that you tell me more about your FitBit Spring Social provider project? Is it modeled after other community-led Spring Social projects? In other words, is it a standalone extension to Spring Social that others may use? If so, tell me where it is in GitHub and I'll be happy to add it to the "Community Projects" section at http://projects.spring.io/spring-social/.

Can (Should) I call a WebService from a Spring MVC app?

I don't know much details about WebService. But I often assume (due to the authentication layer and response format) the code below is a also web service in Spring MVC
#RequestMapping(value = "/rest/member/account",produces={"application/json"}, method=RequestMethod.GET)
public #ResponseBody String getAccountInfo() {
JsonObject account = new JsonObject();
// this queries local DB
account = restAccountService.accountJSON();
return account.toString();
}
Now I need to modify the above code with extra WebService from different application. This extra WebService does not exist yet, I am thinking of creating it with Spring MVC just like the earlier function.
Maybe something like below
...
// this is the so called WebService to different application
SomeWebService webService = new SomeWebService();
boolean valid = webService.checkIfUserValid(username,password);
....
//this queries local DB
if (valid)
account = restAccountService.accountJSON();
...
My questions are
Is the above a common way to do this ?
How do I handled the authentication to access the other WebService ? Because I need to ensure that the call must come from the originating app.

Resources