Migrating JSP code to Spring Controller and Service - java

We are migrating jsp mapping to Spring controller and we want move jsp code to Spring service as we have only scriptlet code in jsp files but the main thing we do not want to change the url that we are calling from UI using ajax call.
Ajax call sample
/ProjectContext/jsp/project/module/downloadFile.jsp
So here .jsp extension will remain same so what should I have to mention in viewResolver.
Please do let me know is there any better way to migrate jsp scriptlet code to spring controller and service.
I have tried below code but not work for me.
#Controller
public class DownloadController {
#Autowired
private DownloadService downloadService;
#RequestMapping(value = "/jsp/project/module/downloadFile.jsp", consumes = APPLICATION_FORM_URLENCODED_VALUE)
public void downloadFileToLocal(HttpServletRequest request, HttpServletResponse response) {
downloadService.downloadFileToLocal(request, response);
}
}

Related

HttpServletRequest - API REST

this is a very noob question. I have a project to do that exemplifies the use of RESTFUL APIs. I am using java spring + MySQL and JSPs for front-end. My question is this. Does HttpServletRequest use REST?
For example, I have one controller with this method in it:
#RequestMapping(value = "/list_events", method = RequestMethod.GET)
public String navigateToEventList(HttpServletRequest request){
request.setAttribute("events",eventService.getAll());
return "listevents";
}
I have the controller class annotated with #Controller. If I swap it to #RestController, it stops working. So, am I using rest in this method for example? And if not, what should I use?
And in my jsp file this is what I have for example:
<c:forEach var="event" items="${events}">
<tr>
<td>${event.id}</td>
<td>${event.title}</td>
<td>${event.description}</td>
<td>${event.type}</td>
<td>${event.date}</td>
<td>${event.location}</td>
</tr>
</c:forEach>
JSP is used when the client needs to display the contents in HTML (web-browser). RESTful web-services used when the client is some other application accepting data responses (it maybe the JavaScript in browser or some other application).
I have the controller class adnotated with #Controller. If I swap it
to #RestController, it stops working.
If you swap it to #RestController the response intended to be JSON, or XML.
You can achieve the same result with annotation #Controller your calss and #ResponseBody on each of the methods (if you need mix of REST and non-REST responses).
What you're doing now is returning the HTML/JSP page to your browser, and it's not a RESTful web-service - it's the first case I described above.
Does HttpServletRequest use REST?
REST means Representational state transfer, and it's architectural style of the application.
HttpServletRequest it's just a requested body from current API. It can be used as either in RESTful or in non-RESTful servces.

HDIV issue while redirecting in Spring MVC Controller

I have inherited some Java Spring MVC code that does internal redirects in the Controller on a form submission
Ex:
Form is submitted to
/login_submit       (POST request)
On success, it is redirected inside controller :-
.....
return "redirect:"+"/user/home"
However, since it is inside code and not using <c:redirect> or <c:url> tags, HDIV fails this form submission with
INVALID_ACTION error
Please help on understanding and resolving this preferably without changing the legacy code too much
Many thanks in advance for your prompt reply!!!
There are two ways you can achieve it,
1) To skip the validation:
#Configuration
#EnableHdivWebSecurity
public class HdivSecurityConfig extends HdivWebSecurityConfigurerAdapter {
#Override
public void addExclusions(ExclusionRegistry registry) {
registry.addUrlExclusions("/user/home");
}
}
2) URL can be generated with HDIV's processor as can be seen below,
LinkUrlProcessor urlProcessor = HDIVUtil.getLinkUrlProcessor(servletContext);
String processUrl = urlProcessor.processUrl(request, "/user/home");
return "redirect:"+processUrl;
I hope this should resolve the issue.

Passing $routeParams from angularjs to spring-MVC controller

This is what I have in my AngularJs controller
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($scope,$routeParams){
$scope.otherId = $routeParams.topicId;
});
This is my Spring Controller
#RequestMapping(value="/controlerM", method = RequestMethod.GET)
public ModelAndView controlerM(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = null;
session=request.getSession(true);
user = (User) session.getAttribute("user");
List<ends1> ends=(List<ends1>) ifriendlistservice.getends(user.getId(),5);
session.setAttribute("MutualFriends", MutualFriends);
model = new ModelAndView("ends");
return model;
I am able to fetch the topicId from my AngularJS page in AngularJS controller (with $scope.otherId), however I am unable to pass this value to my Spring controller, from where I am redirecting to new page.
How should I do this?
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($window){
$window.location.reload();
});
Then server app gets topicId from request's url. You also need to have $locationProvider.html5Mode enabled.
How should I do this?
You shouldn't. Angular's off-hour job is to not let server apps to reload the page. The code above is quick-and-dirty, it can be ok only if you're in the middle of Angular integration into existing project, but the time-frame requires you to partially rely on old code base.
If you really need to make a redirect (e.g. to external page), make an AJAX request, put topicId and whatever there, get redirect url in response, redirect with $window.location.href.
I'm barely familiar with Spring, but the above applies to any server-side application.
Thanks estus,
Issue seems to be resolved...
I had created 2 controller in Spring, One for setting parameter through ajax , and other for redirection.

Java Error Page in web.xml not for all requests

Is it possible to setup error-page but that should be triggered not for all URI's but for example with /custom-path, and for requests with URI's /main-path do not handle errors?
In web.xml i suppose it is only possible to match error page with certain Exception types.
The problem is we have one single war file inside which we have both rest api and html management UI. So if error comes from rest api, it should be rendered as it is and no error page should be displayed.
I had the same problem and I solved it by calling setStatus() on HttpServletResponse instead of throwing exceptions or calling sendError().
Example of my Spring MVC controller:
#RequestMapping(value = "/{ean}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable("id" Long id, HttpServletResponse response) {
// response.sendError(HttpServletResponse.SC_NOT_FOUND)
response.setStatus(HttpServletResponse.SC_NOT_FOUND)
}
This way my RESTful API controllers don't render error pages.

forwarding from spring controller to a jsp file

I am trying to forward my request from a Spring-MVC controller method - to a JSP page.
My controller method is supposed to handle an Ajax request. By forwarding the request to the JSP file, I want the response to the Ajax request to be the (dynamic) HTML output of the JSP file.
What I have tried:
public ModelAndView ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
request.getRequestDispatcher("jspfile").forward(request, response);
return null;
}
This fails and I get "HTTP Status 404"
"jspfiles" is defined in a tiles config file to be directed to the actual jsp file. When I run the following method:
public String ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
return "jspfile";
}
... I get the content of the file as my Ajax response - but JSP tags in that file are not parsed) - hence I conclude that my tiles definition is correct (???).
My JSP file looks like this:
<%=command%>
So I want to get as my Ajax response the string "hello world".
Could you show me an example code of how to achieve my purpose?
Specifically I need to know:
What should be the controller method return type?
What should be the controller method actual return value (if it matters)?
How should I set the jsp file path in the request.getRequestDispatcher(...) so it would be recognized?
Have a look at the controller example here:
http://maestric.com/doc/java/spring/mvc
It's a bit out of date, but the concept of what you must do remains the same. Spring 3 has annotation-based ways to do a lot of what is in that example.

Categories