How to manage error message in Spring MVC - java

I am new to spring MVC .My abc page is have one submit button. On click of submit button, abcHandler called which is inside xyzController.
Just wondering how to achieve this scenario.
-- If some error occurs then it should return some message.
-- It should stay in the same page , for me its abc page.
I have tried this.The problem I am facing is that , i am getting the alert message as "You must have something...",
but it is navigating to error page means a blank page. This is not suppose to happen.I want to show the message and stay in the same page.
How can i achieve easily with spring MVC.
Please suggest some idea.
public class xyzController extends MultiActionController implements InitializingBean {
public ModelAndView abcHandler(HttpServletRequest request,HttpServletResponse response)throws Exception {
// session
HttpSession session = request.getSession(true);
String abc = "";
if(abc != ""){
}else{
String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", error);
}
return new ModelAndView();
}
}
My error.jsp is like this
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${not empty downloaderror}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>

You can implement HandlerExceptionResolver on your own.Refer to this tutorial: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Add an error flag in controller method like this
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("error", true);
return model;
}
In JSP
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${error}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>

You can achieve the scenario by going in following way:
import org.springframework.web.servlet.ModelAndView;
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("ERROR_CODE", "Error Occurred");
model.setViewName("page1");
return model;
}
and your jsp page will be like following:
page1.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
<c:if test="${!empty ERROR_CODE }">
<c:out value="${ERROR_CODE }"></c:out>
</c:if>
</body>
</html>

On validation failure do not return to error page, instead return to same page so your code in else block should be
}else{ String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", abc); }
And also store the errormessage in your modelmap against some key like "errormsg" and on your abc page check for this key and then print the message.

Related

java.lang.IllegalStateException: Cannot (forward | sendRedirect JSP/Java

I read some information about my issue here
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
but I didn't manage to solve my problem with it.
I've got a index.jsp page which should only be accessible to authorized users.
To do so, I use a java file which will feed the session with this information.
When I access my index, if the session is empty I go to my java part to check it, else I just display the content or not.
From my understanding, my issue is that I call this java part twice but I don't know where.
Could you please help me ?
Java code:
public class GroupeUtilisateur extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connBDUtil = null;
String autorise = "";
autorise = CheckAuth.isAllowed(request, response, "IML-Thanact-Admin;IML-Thanact-User");
HttpSession session = request.getSession();
/* Mise en session d'une chaîne de caractères */
session.setAttribute( "autorisation", autorise );
String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
And this is my index.jsp (minus non important parts)
<%# page language="java" import="java.util.*"%>
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<%# page session="true" %>
<head>
// In this script I initialise a datatable and some button will only be available for admin so I need to get the autorisation to
<script type='text/javascript' class='init'>
var authScript = '${sessionScope.autorisation}'; // Récupération de l'autorisation récupérée par GroupeUtilisateur.
</script>
</head>
<body>
<div class ="err"> <c:out value="${sessionScope.message}"/> </div>
<c:set var = "auth" scope = "session" value = "${sessionScope.autorisation}"/> <!-- Récupération de l autorisation pour la session -->
<!--
<div class ="err"> Log Autorisation : [<c:out value = "${auth}"/>] </div>
<div class ="err"> Log Autorisation sans var : [<c:out value = "${sessionScope.autorisation}"/>] </div>
-->
<c:choose>
<c:when test = "${empty auth}">
<div class ="err"> Empy session we go to the java part <c:out value="${sessionScope.autorisation}"/> </div>
<script language="javascript"> document.location.href="./GroupeUtilisateur/" </script>
</c:when>
<c:when test = "${!fn:contains(auth, 'Thanact-Admin') && !fn:contains(auth, 'Thanact-User')}">
<div class ="err">Vous n êtes pas habilité à utiliser cet écran. - [<c:out value = "${auth}" />]</div>
<br/>
<input type="button" name="back" value="Retour" onClick="parent.location='/Thanact/index.jsp'" class="buttonGrey">
</c:when>
<c:otherwise>
<!-- my data-->
</c:otherwise>
</c:choose>
</body>
</html>
Thanks a lot for your help !
EDIT:
Ok so after further investigation I think I located the issue, but still don't know how to fix it.
In fact to see if the user connected belong to the correct AD group we check the session. This is a method used in different app on our ecosystem, I didn't create it.
I think, it is the one who do this :
public class CheckAuth
{
//...
public static String isAllowed(
HttpServletRequest request,
HttpServletResponse response,
String groupMember,
String millPosition,
String forWhat) throws IOException, ServletException
{
//...
String auth = request.getHeader("Authorization");
if (auth == null)
{
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NTLM");
response.flushBuffer();
return "KO" ;
}
//...
}
}
It looks like after setting the header, the servlet is called again.
I need this bit because I can't get the username without.
How may I fix this ?

Display the calculation of servlet before forwarding it to jsp [duplicate]

HTML code appears when I try to execute the jsp page. This appears in the browser.
I tried to change the contentType and language in the tag. But it did not work.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
This is my servlet code.
public class Add extends HttpServlet {
public void service(HttpServletRequest rq, HttpServletResponse rs)throws IOException, ServletException
{
int i=Integer.parseInt(rq.getParameter("t1"));
int j=Integer.parseInt(rq.getParameter("t2"));
int k=i+j;
PrintWriter out=rs.getWriter();
out.println("The sum is:"+k);
RequestDispatcher rd=rq.getRequestDispatcher("/Welcome.jsp");
rd.include(rq,rs);
}
}
I want the code to get rendered and view the output.

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

Spring MVC-Response is not getting from controller using angular

I am implementing simple CRUD Operation using spring restful webservices and angular js.I trying to load all the details when the page is loading.But its not getting any response.
Controller :-
#RestController
public class EmployeeController {
public List<Employee> appList=new ArrayList<Employee>();
#RequestMapping(value="/employee",method=RequestMethod.GET)
public ModelAndView loadEmployee(){
return new ModelAndView("employee", "webemployee", new Employee());
}
#RequestMapping(value="/employees",method = RequestMethod.GET,headers="Accept=application/json")
public List<Employee>loadAllApps() {
Employee app=new Employee();
System.out.println(".........................loadAllApps.............");
app.setAppID("test_id");
app.setAppName("test_name");
appList.add(app);
return appList;
}
#RequestMapping(value="/employees/insert/{appID}/{appDescr}",method = RequestMethod.POST,headers="Accept=application/json")
public List<Employee> addApps(#PathVariable String appID,#PathVariable String appDescr) throws ParseException {
System.out.println("appID"+appID+"appDescr..........."+appDescr);
Employee app=new Employee();
app.setAppID(appID);
app.setAppName(appDescr);
appList.add(app);
return appList;
}
}
Jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="AppManger">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WebService Example</title>
<script data-require="angular.js#*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
</head>
<div ng-controller="appController">
<div>
<table>
<tr ng-repeat="app in appList">
<td >{{ app.appID }}</td>
<td >{{ app.appName }}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var appModule = angular.module('AppManger', []);
appModule.controller('appController', function ($scope,$http) {
var url="http://localhost:8080/Apps";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(url+'/employee').
success(function(data, status, headers, config) {
alert(status);
$scope.appList = data;
});
});
</script>
</script>
</html>
when i am trying to checking status value in $http.get method.its not showing any alert message.Please let me know what issues here.
You seem to call your /employee endpoint but expecting a list of employees , because you assigning data response to the:
$scope.appList = data;
First, change that to the other endpoint you created (/employees) which returns the list.
What is the servlet-path of your mvc dispatcher servlet? This would be my first point of failure to check for. I see that you call:
var url="http://localhost:8080/Apps";
Does that mean that you deploy your app in context 'Apps' or is that your servlet path? If this is the context name then I assume that mvc is resolved to the 'root' path i.e. '/'. If not, check what is servlet path for the dispatcher and add that to your url (on the client side). This would explain why you get 404.
And also, check that you can call your API directly in the browser to rule out the server-side errors as user Chandermani suggested.

Not able to read Model passed by controller on jsp

I am sending Object with help of ModdelAndView in Spring controller, but i am not able to read it on jsp?
JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Tried with EL:
${user}
Try with JSTL:
<c:out value="${user}"></c:out>
</body>
</html>
controller:
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
ModelAndView modelAndView = new ModelAndView("/auth/Home");
modelAndView.addObject("user", "Alex");
return modelAndView;
}
}
I have tried both Spring EL and jstl its not working. Do i need to include anything else?
We need to include org.springframework.web.servlet.ModelAndView instead of org.springframework.web.portlet.ModelAndView;
The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.
update your code as follows
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
return new ModelAndView("yourJspName","user", "Alex");
}
}
then in your jsp, to display the message, you will do
Hello ${user}!
hope this will help you..!

Categories

Resources