HttpSession with Spring 3 MVC - spring

I want to use HttpSession in Spring 3 MVC. I have searched all the web and got this solution at http://forum.springsource.org/showthread.php?98850-Adding-to-stuff-to-the-session-while-using-ResponseBody
Basically, my application auto authenticates user by getting winId and authorizes through LDAP (it's an intranet site).
Here is the flow of the application:
User enters Application URL (http://localhost:8082/eIA_Mock_5) it has a welcome page (index.jsp)
index.jsp gets winId through jQuery and hits login.html (through AJAX) and passes windowsId
login.html (Controller) authenticates through LDAP and gives back 'Valid' String as a response
JavaScript, upon getting the correct response, redirects/loads welcome page i.e. goes to localhost:8082/eIA_Mock_5/welcome.html
Now, I have filter associated with it, which checks if the session is valid for each incoming request. Now the problem is even though I set data on to HttpSession, yet the filter or any other controller fails to get the data through session as a result it doesn't proceeds further.
Here is the code. Could you suggest what is wrong actually?
Home_Controller.java:
#Controller
public class Home_Controller {
public static Log logger = LogFactory.getLog(Home_Controller.class);
#RequestMapping(value = {"/welcome"})
public ModelAndView loadWelcomePage(HttpServletRequest request, HttpServletResponse response)
{
ModelAndView mdv = new ModelAndView();
try {
/*HttpSession session = request.getSession();
UserMasterBean userBean = (UserMasterBean)session.getAttribute("userBean");
String userName = userBean.getWindowsId();
if(userName == null || userName.equalsIgnoreCase(""))
{
mdv.setViewName("homePage");
System.out.println("Unable to authenticate user ");
logger.debug("Unable to authenticate user ");
}
else
{
System.out.println("Welcome User "+userName);
logger.debug("Welcome User "+userName);
*/
mdv.setViewName("homePage");
/*}*/
}
catch (Exception e){
logger.debug("inside authenticateUser ",e);
e.printStackTrace();
}
return mdv;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public #ResponseBody String authenticateUser(#RequestParam String userName, HttpSession session)
{
logger.debug("inside authenticateUser");
String returnResponse = new String();
try {
logger.debug("userName for Authentication " + userName);
System.out.println("userName for Authentication " + userName);
//HttpSession session = request.getSession();
if (userName == null || userName.trim().equalsIgnoreCase(""))
returnResponse = "Invalid";
else
{
System.out.println("uname " + userName);
String ldapResponse = LDAPConnectUtil.isValidActiveDirectoryUser(userName, "");
if (ldapResponse.equalsIgnoreCase("true"))
{
returnResponse="Valid";
System.out.println(userName + " Authenticated");
logger.debug(userName + " Authenticated");
UserMasterBean userBean = new UserMasterBean();
userBean.setWindowsId(userName);
//if(session.getAttribute("userBean")==null)
session.setAttribute("userBean", userBean);
}
else
{
returnResponse = "Invalid";
//session.setAttribute("userBean", null);
System.out.println("Unable to Authenticate the user through Ldap");
logger.debug("Unable to Authenticate the user through Ldap");
}
System.out.println("ldapResponse " + ldapResponse);
logger.debug("ldapResponse " + ldapResponse);
System.out.println("returnResponse " + returnResponse);
}
UserMasterBean u = (UserMasterBean)session.getAttribute("userBean");
System.out.println("winId " + u.getWindowsId());
}
catch(Exception e){
e.printStackTrace();
logger.debug("Exception in authenticateUser ", e);
}
return returnResponse;
}
}
Filter:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
System.out.println("in PageFilter");
boolean flag = false;
HttpServletRequest objHttpServletRequest = (HttpServletRequest)request;
HttpServletResponse objHttpServletResponse = (HttpServletResponse)response;
HttpSession session = objHttpServletRequest.getSession();
String contextPath = objHttpServletRequest.getContextPath();
String servletPath = objHttpServletRequest.getSession().getServletContext().getRealPath(objHttpServletRequest.getServletPath());
logger.debug("contextPath :" + contextPath);
logger.debug("servletPath :" + servletPath);
System.out.println("in PageFilter, contextPath :" + contextPath);
System.out.println("in PageFilter, servletPath :" + servletPath);
if (servletPath.endsWith("\\") || servletPath.endsWith("/") ||
servletPath.indexOf("css") > 0 || servletPath.indexOf("jsp") > 0 ||
servletPath.indexOf("images") > 0 || servletPath.indexOf("js") > 0 ||
servletPath.endsWith("index.jsp") || servletPath.indexOf("xls") > 0 ||
servletPath.indexOf("ini") > 0 || servletPath.indexOf("login.html") > 0 ||
/*servletPath.endsWith("welcome.html") ||*/ servletPath.endsWith("logout.do") )
{
System.out.println("User is trying to access allowed pages like Login.jsp, errorPage.jsp, js, images, css");
logger.debug("User is trying to access allowed pages like Login.jsp, errorPage.jsp, js, images, css");
flag = true;
}
if (flag == false)
{
System.out.println("flag = false");
if (session.getAttribute("userBean") == null)
System.out.println("yes session.userbean is null");
if ((session != null) && (session.getAttribute("userBean") != null))
{
System.out.println("session!=null && session.getAttribute(userId)!=null");
logger.debug("IF Part");
UserMasterBean userBean = (UserMasterBean)session.getAttribute("userBean");
String windowsId = userBean.getWindowsId();
logger.debug("User Id " + windowsId + " allowed access");
System.out.println("User Id " + windowsId + " allowed access");
flag = true;
}
else
{
System.out.println("else .....session!=null && session.getAttribute(userId)!=null");
logger.debug("Else Part");
flag = false;
}
}
if (flag == true) {
try {
System.out.println("before chain.doFilter(request, response)");
chain.doFilter(request, response);
} catch (Exception e) {
e.printStackTrace();
try {
objHttpServletResponse.sendRedirect(contextPath + "/logout.do");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
else
{
try {
System.out.println("before sendRedirect");
objHttpServletResponse.sendRedirect(contextPath + "/jsp/errorPage.jsp");
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("end of PageFilter");
}
index.jsp:
<script type="text/javascript">
//alert("inside s13");
var WinNetwork = new ActiveXObject("WScript.Network");
var userName = WinNetwork.UserName;
alert(userName);
$.ajax({
url: "login.html",
data: "userName="+userName,
success: function(result) {
alert("result == " + result);
if (result == "Valid")
window.location = "http://10.160.118.200:8082/eIA_Mock_5/welcome.html";
}
});
</script>
web.xml has a filter entry with URL pattern as *
I am using Spring 3 MVC.

I think problem in ajax call and setting windows.location after that.
Make sure you set cookie enabled. If you don't do this, your ajax request will lead to new session every time.
When you do window.location = url and this url differ than your current url, it also lead to new session, because cookie is domain related, and you changed domain, for example from localhost to 10.160.118.200.
For each request output sessionid and compare it with previous request. It helps find when session was recreated.
Also this answer can help.

Related

Migrating Apache Struts Action to Spring Rest Controller

I have a webpage whose backend is in Java and the framework is very old (Apache Struts Framework)
The webpage contains buttons textboxes and tables which we can fill and press Add , delete and edit button
All this code is currently written in Action file in java
We need to convert this code and put it in a new Controller file (Rest Controller)
Action files will still be present we just need them till loading JSP onto the page
Once JSP is loaded every button click,event handler (i.e. Add, delete, edit) should be handled by controller
Earlier button clicks were going to Action like formSubmit
We will still need to keep the Action file because we are using Struts framework so we will require action file
Giving an example of two files of how they look after migration -
Apache Struts Action Code-
public final ActionForward updateUserDetails(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
UserAdminForm uForm = (UserAdminForm) form;
UserAdminVO vo = userManager.getUserByUserPk(Integer.parseInt(uForm.getUserPK()));
String olddiscoverId = vo.getDiscoverId();
String oldDiscoverAccess = vo.getDiscoverAccess();
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(uForm.getUserID())) {
manager.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + uForm.getUserID() + ". **");
processErrorMessages(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION,
request);
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
setLandingPageAndOtherDetailsForUserUpdate(uForm, vo);
if (manager.isDebugEnabled()) {
manager.logDebug("User admin VO from user form =" + vo);
manager.logDebug("Old user id : " + uForm.getOldUserID()
+ " New User id : " + uForm.getUserID());
}
DiscoverResponse discoverResponse = null;
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, olddiscoverId, vo);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
vo.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(vo);
syncOtherUsersWithDiscover(vo);
refreshWorkContext(vo);
processSuccessMessage(CConstant.USER_UPDATE_SUCCESS, discoverResponse, request);
} catch (BusinessServiceException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
} catch (BusinessServiceCommonsException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
}
try {
loadCarparks(uForm, vo);
request.getSession(false).setAttribute(PARK_FOR_LOCATION,
uForm.getCarparkList());
} catch (BusinessServiceException e) {
manager.logError("Error in User Display Action ", e);
processBusinessServiceException(e, request);
}
if ("true".equals(uForm.getPasswordExpired())) {
response.sendRedirect(request.getContextPath()
+ "/logout.cprms?doLogout=true");
return null;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
Rest Controller Code -
#PutMapping
public ResponseEntity<Object> updateUser(#RequestBody UserAdminForm userAdminForm, HttpServletRequest request){
List<String> errorMessages = validateUserDetails(userAdminForm);
if(!errorMessages.isEmpty()){
return new ResponseEntity<>(errorMessages, HttpStatus.BAD_REQUEST);
}
ICWorkContext workContext = ControllerUtility.initializeWorkContext(userAdminForm.getLocationId(),request);
var userAdminVO = userManager.getUser(userAdminForm.getUserID());
String oldDiscoverId = userAdminVO.getDiscoverId();
String oldDiscoverAccess = userAdminVO.getDiscoverAccess();
DiscoverResponse discoverResponse = null;
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(userAdminForm.getUserID())) {
LOGGER.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + userAdminForm.getUserID() + ". **");
String errorMessage = messages.getMessage(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION);
return new ResponseEntity<>(errorMessage,HttpStatus.NOT_ACCEPTABLE);
}
setLandingPageAndOtherDetailsForUserUpdate(userAdminForm, userAdminVO,workContext);
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, oldDiscoverId, userAdminVO);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
userAdminVO.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(userAdminVO);
syncOtherUsersWithDiscover(userAdminVO);
refreshWorkContext(userAdminVO,workContext);
} catch (Exception exception) {
LOGGER.logError("Error in Update User API", exception);
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
Map<String, Object> response = new HashMap<>(2);
List<String> successMessages = new ArrayList<>(2);
successMessages.add(messages.getMessage(CConstant.USER_UPDATE_SUCCESS));
getDiscoverResponseMessage(discoverResponse, response, successMessages);
response.put(SUCCESS_MESSAGE,successMessages);
return new ResponseEntity<>(response,HttpStatus.OK);
}
I want to migrate this Action Code to Rest Controller -
public final ActionForward displayAllLeaves(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException,
ServletException {
boolean checkFlag = true;
LumpConfigFB lumpConfigFB = (LumpConfigFB) form;
storeProductWithoutDNAToRequest(request);
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
BusinessServiceException businessServiceException = new BusinessServiceException(
CPRMSConstant.NO_C_ERROR);
businessServiceException
.setErrorCode(CConstant.NO_C_ERROR);
processBusinessServiceException(businessServiceException,
request);
return mapping
.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
// populateVO
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
lumpConfigFB.setMappedLumpDefList(mappedLumpDefList);
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
lumpConfigFB.setUnmappedLumpDefList(unMappedLumpDefList);
}
} else {
lumpConfigFB.setMappedLumpDefList(null);
lumpConfigFB.setUnmappedLumpDefList(null);
BusinessServiceException businessServiceException = new BusinessServiceException(
CConstant.LEAF_NOT_FOUND_ERROR);
businessServiceException
.setErrorCode(CConstant.LEAF_NOT_FOUND_ERROR);
processBusinessServiceException(businessServiceException,
request);
checkFlag = false;
}
if (null != request.getAttribute("jobid")
&& !"".equals(request.getAttribute("jobid"))) {
String jobId = (String) request.getAttribute("jobid");
ActionErrors actionErrors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if ("failure".equals(request.getAttribute("jobid").toString())) {
String errorCode = (String) request
.getAttribute("errorcode");
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(errorCode));
saveErrors(request, (ActionMessages) actionErrors);
} else {
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(CConstant.AGGR_QUEUE_SUCCESS,
jobId));
messages.add(actionErrors);
saveMessages(request, messages);
}
}
} catch (BusinessServiceException businessServiceException) {
processBusinessServiceException(businessServiceException, request);
checkFlag = false;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
I have also written a Rest Controller Code for this Action file but I am not sure If I am going right -
public class LeavesController {
#Autowired
private LumpConfigManager lumpConfigManager;
#GetMapping
public ResponseEntity<List<LumpConfigVO>> getAllLeaves(HttpServletRequest request) {
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
throw new BusinessServiceException(CPRMSConstant.NO_CARPARK_ERROR);
}
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
}
return ResponseEntity.ok(lumpConfigVO);
} else {
throw new BusinessServiceException(CPRMSConstant.LEAF_NOT_FOUND_ERROR);
}
} catch (BusinessServiceException businessServiceException) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, businessServiceException.getMessage(), businessServiceException);
}
}
// helper method for populating LumpConfigVO from LumpConfigFB
private void populateLumpConfigVO(LumpConfigFB lumpConfigFB, LumpConfigVO lumpConfigVO) {
// implementation here
}
// helper method for storing product without DNA to request
private void storeProductWithoutDNAToRequest(HttpServletRequest request) {
// implementation here
}
// other helper methods and properties omitted
}

Servlet not returning html code to ajax

I have one jsp where below ajax call is made to get some data from servlet which will return html table in response :
function searchStudent() {
var lname = document.getElementsByName("lname");
var fname = document.getElementsByName("fname");
var email = document.getElementsByName("email");
var submit = document.getElementById("search");
xmlhttp.onreadystatechange=useResponse;
xmlhttp.open("GET", "SearchUser?
submit="+submit+"&fname="+fname+"&lname="+lname+"&email"+email,
true);
xmlhttp.send(null);
}
function useResponse() {
alert(xmlhttp.status+" "+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("hi"+xmlHttp.responseText);
document.getElementById("demo").innerHTML=xmlhttp.responseText;
alert("hi"+xmlHttp.responseText);
}
}
Function 'searchStudent()' is called on a button click.
Below is the servlet doGet() method :
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String fname="";
String lname="";
String email="";
String button="";
button = request.getParameter("submit");
db = new DbOperation();
HttpSession session = request.getSession();
session.removeAttribute("msg");
if(button!=null && button.equalsIgnoreCase("Search")){
fname=request.getParameter("fname")==null?"":request.getParameter("fname");
lname=request.getParameter("lname")==null?"":request.getParameter("lname");
email=request.getParameter("email")==null?"":request.getParameter("email");
Admin admin =(Admin) session.getAttribute("Admin");
int adminId=0;
if(admin!=null)
adminId=admin.getId();
ArrayList<Student> student = new ArrayList<Student>();
student= db.searchStudent(fname,lname,email,adminId);
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
if(student!=null && student.size()>0){
session.setAttribute("student", student);
StringBuilder std= new StringBuilder();
std.append("<table border='1'><th>Id</th><th>First_name</th><th>Last_Name</th><th>Email</th><th>State</th><th>City</th>");
for(Student st :student ){
std.append("<tr><td>"+st.getId()+"</td><td>"+st.getFname()+"</td><td>"+st.getLname()+"</td><td>"+st.getEmail()+"</td><td>"+st.getState()+"</td><td>"+st.getCity()+"</td></tr>");
}
std.append("<table>");
//pw.write(std.toString());
pw.write(std.toString());
//pw.write("<h3>here</h3>");
}else{
pw.write("<h3>Student doesn't exists</h3>");
/*RequestDispatcher rd = request.getRequestDispatcher("AdminServlet?msg1=Student doesn't exists");
rd.forward(request, response);*/
}
}
}
The html returned by servlet is directly displayed in console and not coming to the jsp from where ajax call is made.
alert("hi"+xmlHttp.responseText); is also not getting populates

Wicket.Ajax.ajax working not like ajax, but like normal http query

i use Wicket.Ajax.ajax in pair with AbstractDefaultAjaxBehavior to sent some javascript calculated data to the java. But after event has fired from javascript and comes to Java, browser has been redirected to callback url.
...web/product/1?7&6-1.IBehaviorListener.0-idsPanelPlace%3Floggged_id=332797
logggedidAjax = new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
String componentMarkupId = getMarkupId();
Map<String, Object> map = new HashMap<>();
map.put("callbackUrl", logggedidAjax.getCallbackUrl());
PackageTextTemplate ptt = new PackageTextTemplate(VKIDsPanel.class, "id_callback.js");
OnDomReadyHeaderItem onDomReadyHeaderItem = OnDomReadyHeaderItem.forScript(ptt.asString(map));
response.render(onDomReadyHeaderItem);
}
};
add(logggedidAjax);
As for js code -
var wcall = Wicket.Ajax.ajax({ u: '${callbackUrl}' + '?loggged_id='+ response.session.mid });
Why browser redirected to the url, since it is Ajax? How to prevent redirection?
I'm not sure what's going wrong in your code, but the following should be easier:
logggedidAjax = new AjaxEventBehavior("domready") {
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
String loggedId = "return {'logged_id': response.session.mid}";
attributes.getDynamicExtraParameters().add(loggedId);
}
#Override
protected void onEvent(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
};
add(logggedidAjax);

Spring mvc When using enctype="multipart/form-data" modelAttribute values equal null in the controller

I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}

Google Authentication API: How to get the user's gmail address

I've been studying the Google authentication API (AuthSub)... My question is, how do I get the user's account information (at least their Gmail address) after the authentication has passed?
Because currently, all I get back from the authentication process is a token granting me access to which ever Google service I have specified in the scope, but there's no easy way to even get the user's login id (Gmail address) as far as I can tell...
If so, what Google service allows me to access the user's information?
Google Authentication API is a token based system to authenticate a valid user. It does not expose any of other interface that allows to get account holder information back to authorizer.
Using the Google AppEngine GData services, you can request the user to give you access to their Google Mail, Calendar, Picasa, etc. Check it out here.
You can get some of the data through the OpenID API, with the ax extension. If you are authenticating with other methods, best I found is calling https://www-opensocial.googleusercontent.com/api/people/#me/#self and it will get you name, email and picture. Be sure to have http://www-opensocial.googleusercontent.com/api in scopes when authenticating.
[ValidateInput(false)]
public ActionResult Authenticate(string returnUrl)
{
try
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method start ");
var response = openid.GetResponse();
if (response == null)
{
try
{
string discoveryuri = "https://www.google.com/accounts/o8/id";
//OpenIdRelyingParty openid = new OpenIdRelyingParty();
var fetch = new FetchRequest();// new
var b = new UriBuilder(Request.Url) { Query = "" };
var req = openid.CreateRequest(discoveryuri, b.Uri, b.Uri);
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
req.AddExtension(fetch);
return req.RedirectingResponse.AsActionResult();
}
catch (ProtocolException ex)
{
logger.ErrorFormat(" LoginController : Authenticate method has error, Exception:" + ex.ToString());
ViewData["Message"] = ex.Message;
return View("Login");
}
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :when responce not null ");
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
logger.Info("" + response.Status + "] LoginController : Authenticate method : responce status ");
var fetchResponse = response.GetExtension<FetchResponse>();
string email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email);
string userIPAddress = HttpContext.Request.UserHostAddress;
SecurityManager manager = new SecurityManager();
int userID = manager.IsValidUser(email);
if (userID != 0)
{
ViewBag.IsFailed = "False";
logger.Info("" + userID + "] LoginController : Authenticate method : user id id not null ");
Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
Session["UserEmail"] = email;
FormsAuthentication.SetAuthCookie(email, false);
WebSession.UserEmail = email;
WebSession.UserID = userID;
UserManager userManager = new UserManager();
WebSession.AssignedSites = userManager.GetAssignedSites(userID);
if (!string.IsNullOrEmpty(returnUrl))
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method : retutn url not null then return Redirect ");
return Redirect(returnUrl);
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method : retutn url null then return RedirectToAction ");
//
return Redirect("/Home");
}
}
else
{
ViewBag.IsFailed = "True";
logger.Info("" + returnUrl + "] LoginController : Authenticate method :user id null ");
if (!string.IsNullOrEmpty(returnUrl))
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :and return Redirect ");
return Redirect(returnUrl);
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :and return RedirectToAction ");
return View("Index");
}
}
case AuthenticationStatus.Canceled:
logger.Info("" + response.Status + "] LoginController : Authenticate method : AuthenticationStatus.Canceled and return view ");
ViewData["Message"] = "Canceled at provider";
return View("Login");
case AuthenticationStatus.Failed:
logger.Info("" + response.Status + "] LoginController : Authenticate method : AuthenticationStatus.Failed and return view ");
logger.Error(response.Exception.Message);
ViewData["Message"] = response.Exception.Message;
return View("Login");
}
}
logger.Info("" + returnUrl + "] LoginController : Authenticate method end and return EmptyResult");
return new EmptyResult();
}
catch (Exception ex)
{
logger.Error(" LoginController : Authenticate method ", ex);
throw;
}
}

Resources