How to handle invalid authentication in liferay sign in portlet - liferay

Im trying to customize the login portlet for my purpose using this portlet login sample.
But when i login with test#liferay.com with a wrong password it shows "web page is not available"
SignInPortlet.java
public class SignInPortlet extends MVCPortlet {
#Override
public void processAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
String className = "com.liferay.portlet.login.action.LoginAction";
PortletConfig portletConfig = getPortletConfig();
NoRedirectActionResponse noRedirectActionResponse =
new NoRedirectActionResponse(actionResponse);
try {
PortletActionInvoker.processAction(
className, portletConfig, actionRequest,
noRedirectActionResponse);
}
catch (Exception e) {
_log.error(e, e);
}
String login = ParamUtil.getString(actionRequest, "login");
String password = ParamUtil.getString(actionRequest, "password");
String rememberMe = ParamUtil.getString(actionRequest, "rememberMe");
if (Validator.isNull(noRedirectActionResponse.getRedirectLocation())) {
actionResponse.setRenderParameter("login", login);
actionResponse.setRenderParameter("rememberMe", rememberMe);
}
else {
String redirect =
PortalUtil.getPathMain() + "/portal/login?login=" + login +
"&password=" + password + "&rememberMe=" + rememberMe;
actionResponse.sendRedirect(redirect);
}
}
private static Log _log = LogFactoryUtil.getLog(SignInPortlet.class);
}
View.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%# taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%# page import="com.liferay.portal.CookieNotSupportedException" %>
<%# page import="com.liferay.portal.NoSuchUserException" %>
<%# page import="com.liferay.portal.PasswordExpiredException" %>
<%# page import="com.liferay.portal.UserEmailAddressException" %>
<%# page import="com.liferay.portal.UserLockoutException" %>
<%# page import="com.liferay.portal.UserPasswordException" %>
<%# page import="com.liferay.portal.UserScreenNameException" %>
<%# page import="com.liferay.portal.kernel.language.LanguageUtil" %>
<%# page import="com.liferay.portal.kernel.util.ClassResolverUtil" %>
<%# page import="com.liferay.portal.kernel.util.Constants" %>
<%# page import="com.liferay.portal.kernel.util.GetterUtil" %>
<%# page import="com.liferay.portal.kernel.util.HtmlUtil" %>
<%# page import="com.liferay.portal.kernel.util.MethodKey" %>
<%# page import="com.liferay.portal.kernel.util.ParamUtil" %>
<%# page import="com.liferay.portal.kernel.util.PortalClassInvoker" %>
<%# page import="com.liferay.portal.kernel.util.PropsUtil" %>
<%# page import="com.liferay.portal.model.Company" %>
<%# page import="com.liferay.portal.security.auth.AuthException" %>
<%# page import="javax.portlet.WindowState" %>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<c:choose>
<c:when test="<%= themeDisplay.isSignedIn() %>">
<%
String signedInAs = user.getFullName();
if (themeDisplay.isShowMyAccountIcon()) {
signedInAs = "" + signedInAs + "";
}
%>
<%= LanguageUtil.format(pageContext, "you-are-signed-in-as-x", signedInAs, false) %>
</c:when>
<c:otherwise>
<%
MethodKey methodKey = new MethodKey(ClassResolverUtil.resolveByPortalClassLoader("com.liferay.portlet.login.util.LoginUtil"), "getLogin", HttpServletRequest.class, String.class, Company.class);
String login = GetterUtil.getString((String)PortalClassInvoker.invoke(false, methodKey, request, "login", company));
boolean rememberMe = ParamUtil.getBoolean(request, "rememberMe");
%>
<portlet:actionURL var="loginURL" />
<aui:form action="<%= loginURL %>" method="post" name="fm">
<aui:input name="saveLastPath" type="hidden" value="<%= false %>" />
<aui:input name="<%= Constants.CMD %>" type="hidden" value="<%= Constants.UPDATE %>" />
<aui:input name="rememberMe" type="hidden" value="<%= rememberMe %>" />
<liferay-ui:error exception="<%= AuthException.class %>" message="authentication-failed" />
<liferay-ui:error exception="<%= CookieNotSupportedException.class %>" message="authentication-failed-please-enable-browser-cookies" />
<liferay-ui:error exception="<%= NoSuchUserException.class %>" message="please-enter-a-valid-login" />
<liferay-ui:error exception="<%= PasswordExpiredException.class %>" message="your-password-has-expired" />
<liferay-ui:error exception="<%= UserEmailAddressException.class %>" message="please-enter-a-valid-login" />
<liferay-ui:error exception="<%= UserLockoutException.class %>" message="this-account-has-been-locked" />
<liferay-ui:error exception="<%= UserPasswordException.class %>" message="please-enter-a-valid-password" />
<liferay-ui:error exception="<%= UserScreenNameException.class %>" message="please-enter-a-valid-screen-name" />
<table class="lfr-table">
<tr>
<td>
<aui:input name="login" style="width: 120px;" type="text" value="<%= HtmlUtil.escape(login) %>" />
</td>
</tr>
<tr>
<td>
<aui:input name="password" style="width: 120px;" type="password" value="" />
<span id="<portlet:namespace />passwordCapsLockSpan" style="display: none;"><liferay-ui:message key="caps-lock-is-on" /></span>
</td>
</tr>
<c:if test='<%= company.isAutoLogin() && !GetterUtil.getBoolean(PropsUtil.get("session.disabled")) %>'>
<tr>
<td>
<aui:input checked="<%= rememberMe %>" name="rememberMe" type="checkbox" />
</td>
</tr>
</c:if>
</table>
<br />
<input type="submit" value="<liferay-ui:message key="sign-in" />" />
</aui:form>
<c:if test="<%= renderRequest.getWindowState().equals(WindowState.MAXIMIZED) %>">
<aui:script>
Liferay.Util.focusFormField(document.<portlet:namespace />fm.<portlet:namespace />login);
</aui:script>
</c:if>
<aui:script use="aui-base">
A.one('#<portlet:namespace />password').on(
'keypress',
function(event) {
Liferay.Util.showCapsLock(event, '<portlet:namespace />passwordCapsLockSpan');
}
);
</aui:script>
</c:otherwise>
</c:choose>
Does any one know how to solve this?

I changed the portlet code like this .Now it is ok
public class SignInPortlet extends MVCPortlet {
#Override
public void processAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
String className = "com.liferay.portlet.login.action.LoginAction";
PortletConfig portletConfig = getPortletConfig();
NoRedirectActionResponse noRedirectActionResponse =
new NoRedirectActionResponse(actionResponse);
try {
PortletActionInvoker.processAction(
className, portletConfig, actionRequest,
noRedirectActionResponse);
}
catch (Exception e) {
_log.error(e, e);
}
String login = ParamUtil.getString(actionRequest, "login");
String password = ParamUtil.getString(actionRequest, "password");
String rememberMe = ParamUtil.getString(actionRequest, "rememberMe");
Object object = SessionErrors.get( actionRequest, AuthException.class.getName() );
if (( object != null ) || Validator.isNull(noRedirectActionResponse.getRedirectLocation())) {
actionResponse.setRenderParameter("login", login);
actionResponse.setRenderParameter("rememberMe", rememberMe);
}
else {
String redirect =
PortalUtil.getPathMain() + "/portal/login?login=" + login +
"&password=" + password + "&rememberMe=" + rememberMe;
actionResponse.sendRedirect(redirect);
}
}
private static Log _log = LogFactoryUtil.getLog(SignInPortlet.class);
}

Related

Render()'s Method different reactions

I have my render() method with no code.
And I have this action-method:
#ProcessAction(name = "viewBook")
public void viewBook(ActionRequest actionRequest,ActionResponse actionResponse) throws SystemException, PortalException {
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
How can I rewrite this "GET" method into render() method? I mean I need to run
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
super.render(renderRequest, renderResponse)
}
in the default situation and
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
\\THIS CODE IS NOT WORKING, IT'S JUST TO SHOW WHAT I WANT!
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
when I need to use viewBook() method. How can I parametrize(?) render() method?
Update:
For more details I attached one screenshot:
Meanwhile in my action.jsp:
<liferay-ui:icon-menu>
<portlet:actionURL name="deleteBook" var="deleteURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:actionURL>
<portlet:renderURL name="viewBook" var="viewURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<portlet:renderURL var="editBookURL" name="viewEdit">
<portlet:param name="bookId" value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<liferay-ui:icon image="add" message="View" url="${viewURL.toString()}" />
<liferay-ui:icon image="add" message="Edit" url="${editBookURL.toString()}" />
<liferay-ui:icon-delete image="delete" message="Delete" url="${deleteURL.toString()}" />
In my view_book.jsp:
<%#page import="com.softwerke.FinalStrings"%>
<%#page import="com.softwerke.model.Book"%>
<%#page import="com.softwerke.service.BookLocalServiceUtil"%>
<%#page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%# include file="/html/init.jsp"%>
<portlet:renderURL var="backURL">
<portlet:param name="jspPage" value="/html/view.jsp"/>
</portlet:renderURL>
<liferay-ui:header backURL="${backURL}" title="Back" />
<%
Book book = (Book) request.getAttribute(FinalStrings.BOOK_ENTRY);
%>
<aui:form>
<aui:model-context bean="${book}" model="${Book.class}" />
<aui:input name="bookName" label="Book Name" disabled="true"/>
<aui:input type="textarea" name="description" label="Description" disabled="true"/>
<aui:input name="authorName" label="Author Name" disabled="true"/>
<aui:input name="price" label="Price" disabled="true"/>
</aui:form>
According to my task I can not use Action URL here. What should I do???
You can send a command param to the render, so you can split the logic into two or more render methods, depending on the command, or maybe easier, invoke a mvcPath without the need of implementing anything in render(). Include something like this in the jsp with your list of books:
<portlet:renderURL var="myBookURL">
<portlet:param name="mvcPath" value="/view_book.jsp" />
<portlet:param name="bookId" value="<%= someBookId %>" />
</portlet:renderURL>
View My Book
You just need a view_book.jsp with something like:
<%
long bookId = ParamUtil.getLong(request, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
%>
Hope it helps.

Search box in search container

hi folks as per Search box in Search conatiner Image is here !
i just wanted to ask when the user type a name in search box then the particular field should be display.i am putting my view.jsp code is here also??
Vuew.jsp
<%#page import="com.proliferay.servicebuilder.service.BlobDemoLocalServiceUtil"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%#page import="javax.portlet.PortletURL"%>
<%# taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%# taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<liferay-theme:defineObjects />
<portlet:defineObjects />
<style>
.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 20%;
}
</style>
<%
PortletURL addEmp = renderResponse.createRenderURL();
addEmp.setParameter("mvcPath", "/html/blobdemo/add.jsp");
PortletURL homeURL = renderResponse.createRenderURL();
PortletURL iteratorURL=renderResponse.createRenderURL();
iteratorURL.setParameter("mvcPath", "/html/blobdemo/display_student.jsp");
PortletURL addEmployee = renderResponse.createRenderURL();
addEmployee.setParameter("mvcPath", "html/blobdemo/add_emp.jsp");
PortletURL employeeDetailsURL = renderResponse.createRenderURL();
employeeDetailsURL.setParameter("mvcPath", "/html/empref/student_details.jsp");
PortletURL displaySearchStudent = renderResponse.createRenderURL();
displaySearchStudent.setParameter("mvcPath", "/html/blobdemo/view.jsp");
%>
Home<br/><br/>
<div class="wrapper">
<button class="btn btn-info" >Employee Referral</button>
</div>
<button class="btn btn-info">Refer an Employee</button>
<!-- <form class="form-search">
<input type="text" class="input-medium search-query" style="margin-left: 571px;margin-top:-25px;"> -->
<!-- --search button -->
<input name="<portlet:namespace/>search" type="text" style="margin-top: -42px;margin-left: 663px;"/>
<input type="submit" label="" value="search"
style=" margin-top: -40px" formaction="" name="stdForm" >
<!-- -search button ends here! -->
<liferay-ui:search-container emptyResultsMessage="There is no data to display">
<liferay-ui:search-container-results
results="<%=BlobDemoLocalServiceUtil.getBlobDemos(
searchContainer.getStart(), searchContainer.getEnd())%>"
total="<%= BlobDemoLocalServiceUtil.getBlobDemosCount() %>" />
<liferay-ui:search-container-row className="com.proliferay.servicebuilder.model.BlobDemo" modelVar="aBlobDemo">
<portlet:resourceURL var="viewURL"> <portlet:param name="dataId" value="<%=String.valueOf(aBlobDemo.getBlobId())%>" />
</portlet:resourceURL>
<liferay-ui:search-container-column-text
value="<%=String.valueOf(row.getPos() + 1)%>" name="Serial No" />
<liferay-ui:search-container-column-text property="customer" name="customer" />
<liferay-ui:search-container-column-text property="referral" name="referral ID" />
<liferay-ui:search-container-column-text property="candidateName" name="Candidate Name" />
<liferay-ui:search-container-column-text property="contactNumber" name="Contact Number" />
<liferay-ui:search-container-column-text property="qualification" name="Qualification " />
<liferay-ui:search-container-column-text property="interviewdateandtime" name="interviewdateandtime" />
<liferay-ui:search-container-column-text property="tenetavijoiningdate" name="Tenetavijoiningdate" />
<liferay-ui:search-container-column-text property="status" name="Status " />
<liferay-ui:search-container-column-text property="actualjoiningdate" name="Actualjoiningdate" />
<liferay-ui:search-container-column-text property="tanurityindays" name="Tanurityindays " />
<liferay-ui:search-container-column-jsp path="/html/blobdemo/action.jsp" align="right" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
</form>
yeah itz been completd , we can write a dynamic query for this and rebuild the sevices.
steps to do this.
1:- first we have to write a dynamic query in localserviceimpl.java so that when we rebuild the services it will generate the methods in localserviceutil.java
2:- and we can call in this methods in search form search container using display terms .
3:- we can easily search using any keyvalue.
package com.data.dbservice.service.impl;
import java.util.List;
import com.data.dbservice.service.base.StudentLocalServiceBaseImpl;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.Junction;
import com.liferay.portal.kernel.dao.orm.Property;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.Validator;
import com.data.dbservice.model.Student;
import com.data.dbservice.service.StudentLocalServiceUtil;
/**
* The implementation of the student local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {#link com.data.dbservice.service.StudentLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* #author Abhishek
* #see com.data.dbservice.service.base.StudentLocalServiceBaseImpl
* #see com.data.dbservice.service.StudentLocalServiceUtil
*/
public class StudentLocalServiceImpl extends StudentLocalServiceBaseImpl {
public List getSerachStudents(String firstName,String lastName,int studentAge,int studentGender,String studentAddress,
boolean andSearch, int start, int end, OrderByComparator orderByComparator)
throws SystemException
{
DynamicQuery dynamicQuery = buildStudentDynamicQuery(firstName, lastName, studentAge, studentGender, studentAddress, andSearch);
return StudentLocalServiceUtil.dynamicQuery(dynamicQuery, start, end, orderByComparator);
}
public int getSearchStudentsCount(String firstName,String lastName,int studentAge,int studentGender,String studentAddress,boolean andSearch)
throws SystemException
{
DynamicQuery dynamicQuery = buildStudentDynamicQuery(firstName, lastName, studentAge, studentGender, studentAddress, andSearch);
return (int)StudentLocalServiceUtil.dynamicQueryCount(dynamicQuery);
}
protected DynamicQuery buildStudentDynamicQuery(String firstName,String lastName,int studentAge,int studentGender,String studentAddress,boolean andSearch)
{
Junction junction = null;
if(andSearch)
junction = RestrictionsFactoryUtil.conjunction();
else
junction = RestrictionsFactoryUtil.disjunction();
if(Validator.isNotNull(firstName))
{
Property property = PropertyFactoryUtil.forName("firstName");
String value = (new StringBuilder("%")).append(firstName).append("%").toString();
junction.add(property.like(value));
}
if(Validator.isNotNull(lastName))
{
Property property = PropertyFactoryUtil.forName("lastName");
String value = (new StringBuilder("%")).append(lastName).append("%").toString();
junction.add(property.like(value));
}
if(studentAge > 0)
{
Property property = PropertyFactoryUtil.forName("studentAge");
junction.add(property.eq(Integer.valueOf(studentAge)));
}
if(studentGender > 0)
{
Property property = PropertyFactoryUtil.forName("studentGender");
junction.add(property.eq(Integer.valueOf(studentGender)));
}
if(Validator.isNotNull(studentAddress))
{
Property property = PropertyFactoryUtil.forName("studentAddress");
String value = (new StringBuilder("%")).append(studentAddress).append("%").toString();
junction.add(property.like(value));
}
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(Student.class, getClassLoader());
return dynamicQuery.add(junction);
}
}

Passing parameters to Liferay PortletURL

I would like to validate the request of an user by doing he types his personal key. First of all he does the request, now the portlet redirects to a second jsp file where he validates with the key and finally if it is ok the portlet complete the request otherwise returns to the first step.
Here is the code,
1.- view.jsp (the request)
<%# include file="/html/blue/init.jsp" %>
Welcome to our Colors workflow
<br/>
<%
PortletURL redirectURL = renderResponse.createActionURL();
redirectURL.setParameter(ActionRequest.ACTION_NAME, "redirect");
%>
<aui:form name="fmAdd" method="POST" action="<%= redirectURL.toString() %>">
<aui:input type="hidden" name="myaction" value="add" />
<aui:button type="submit" value="Add New Box"/>
</aui:form>
<aui:form name="fmList" method="POST" action="<%= redirectURL.toString() %>">
<aui:input type="hidden" name="myaction" value="list" />
<aui:button type="submit" value="Show All Boxes"/>
</aui:form>
2.- the java code,
public void redirect(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String action = ParamUtil.getString(actionRequest, "myaction");
PortletURL redirectURL = null;
String redirectJSP = "/checkuser.jsp";
if(action != null) {
String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest),
portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE);
redirectURL.setParameter("myaction", action);
redirectURL.setParameter("jspPage", redirectJSP);
}
actionResponse.sendRedirect(redirectURL.toString());
}
3._ checkuser.jsp (the user validate with his key)
<%# include file="/html/blue/init.jsp" %>
<%
PortletURL checkUserURL = renderResponse.createActionURL();
checkUserURL.setParameter(ActionRequest.ACTION_NAME, "checkUser");
String myaction = renderRequest.getParameter("myaction");
%>
<p> Your action: <%= myaction %> </p>
<aui:form name="fm" method="POST" action="<%= checkUserURL.toString() %>">
<aui:input type="hidden" name="myaction" value="<%= myaction %>" />
<aui:input type="text" name="key" value=""/>
<aui:button type="submit" value="Save"/>
</aui:form>
In this phase I am getting the first problem because I do not see the value of the request (myaction variable). This is only for debug.
4._ the java code that catches the last form,
public void checkUser(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String key = ParamUtil.getString(actionRequest, "key");
String action = ParamUtil.getString(actionRequest, "myaction");
String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest),
portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE);
String redirectJSP = "/view.jsp";
if(key != null) {
if(key.equalsIgnoreCase("blue")) {
if(action != null) {
if(action.equalsIgnoreCase("add")) {
redirectJSP = "/update.jsp";
}
if(action.equalsIgnoreCase("list")) {
redirectJSP = "/list.jsp";
}
}
}
}
redirectURL.setParameter("jspPage", redirectJSP);
actionResponse.sendRedirect(redirectURL.toString());
}
In this phase the portlet always goes to view.jsp where the user does the request. I am thinking both key and action variables are null or at least one of them.
What am I doing wrong?
Regards,
Jose
In Liferay, the parameters are set with a namespace so that they don't cause problems when there are more than 1 portlet on the page. Especially if you have the exact same portlet on the page twice! So when you're setting myaction, it really gets set to something like _myportlet_INSTANCE_xlka_myaction or something similar.
You can use com.liferay.portal.kernel.util.ParamUtil to help you get your parameters without having to worry about the scoping. For example:
ParamUtil.getString(request, "myaction");

AUI is not defined and Liferay is not defined error in jsp page?

I am using my custom portlet in liferay.
but somehow when i run my portlet i m having following error in error console
Timestamp: 12/10/2012 12:33:19 PM
Error: ReferenceError: AUI is not defined
Source File: http://localhost:8080/eMenuAdvertise-portlet/js/jquery.min.js
Line: 4
Timestamp: 12/10/2012 12:34:21 PM
Error: ReferenceError: Liferay is not defined
Source File: http://localhost:8080/eMenuAdvertise-portlet/js/jquery.min.js
Line: 3
So why this error comes in my jsp page for some jquery?
<%# page import="net.sf.jasperreports.engine.JRException" %>
<%# page import="net.sf.jasperreports.engine.JasperExportManager" %>
<%# page import="net.sf.jasperreports.engine.JasperFillManager" %>
<%# page import="net.sf.jasperreports.engine.JasperPrint" %>
<%# page import="net.sf.jasperreports.engine.JasperPrintManager" %>
<%#page import="com.liferay.portal.model.Role"%>
<%# include file="/init.jsp"%>
<%#page import="com.liferay.portal.model.Organization"%>
<%#page import="com.liferay.portal.util.PortalUtil"%>
<style>
.borderColor{border: 1px solid #C62626;}
</style>
<portlet:renderURL var="ajaxaddnewrestURL">
<portlet:param name="jspPage" value="/jsps/ajaxnewrest.jsp" />
</portlet:renderURL>
<portlet:renderURL var="editrestURL">
<portlet:param name="jspPage" value="/jsps/Ajax_editrest.jsp" />
</portlet:renderURL>
<portlet:renderURL var="restListURL">
<portlet:param name="jspPage" value="/jsps/rest.jsp" />
</portlet:renderURL>
<portlet:renderURL var="reportURL">
<portlet:param name="jspPage" value="/htmlreport/report.html" />
</portlet:renderURL>
<portlet:renderURL var="renderURL ">
<portlet:param name="param-name" value="param-value" />
</portlet:renderURL>
<%-- <portlet:resourceURL var="ReportId" id="generate_report"></portlet:resourceURL> --%>
<portlet:resourceURL var="addToDo" id="generate_report"></portlet:resourceURL>
<script type="text/javascript" src="<%=request.getContextPath()%>/lib/chosen/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.3/themes/south-street/ui.all.css" type="text/css">
<script src="<%=request.getContextPath()%>/js/datepickernew/jquery-1.8.3.js"></script>
<script src="<%=request.getContextPath()%>/js/datepickernew/jquery-ui.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.validate.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/lib/chosen/chosen.jquery.min.js"></script>
<%
System.setProperty("java.awt.headless", "true");
System.out.println(java.awt.GraphicsEnvironment.isHeadless());
String loading_img_path = request.getContextPath()+"/img/ajax_loader.gif";
boolean isReseller=false; ///advertiser if flag is false else Reseller
List<Role> role_list_page=themeDisplay.getUser().getRoles();
for(Role role_name:role_list_page){
if(role_name.getName().equals("Reseller")){
isReseller=true;
break;
}
}%>
<script>
</script>
<script>
$(function() {
$("#Start_validBeforeDatepicker").datepicker({
numberOfMonths: 1,
showButtonPanel: true,
onClose: function( selectedDate ) {
$( "#End_validAfterDatepicker" ).datepicker( "option", "minDate", selectedDate );
}
});
$("#End_validAfterDatepicker").datepicker({
numberOfMonths: 1,
showButtonPanel: true,
onClose: function( selectedDate ) {
$( "#Start_validBeforeDatepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});
// $("#validBeforeDatepicker").datepicker({ minDate: 0 });
$('#Start_validBeforeDatepicker,#End_validAfterDatepicker').datepicker();
});
</script>
<script type="text/javascript">
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({
allow_single_deselect : true
});
$(document).ready(function() {
$(".ui-datepicker").css("display","none");
});
</script>
<script type="text/javascript">
function update_rest(addToDo){
var camp_ID =document.getElementById('camp_id').value;
var f_start_date =document.getElementById('Start_validBeforeDatepicker').value;
var f_end_date =document.getElementById('End_validAfterDatepicker').value;
$.ajax({
url :addToDo,
data: {"rest_name":camp_ID,
"f_start_date":f_start_date,
"f_end_date":f_end_date,
"CMD":camp_ID},
type: "GET",
timeout: 20000,
dataType: "text",
success: function(data) {
alert("");
alert ( " liferay url : "+ Liferay.PortletURL.createRenderURL());
alert( "row1: " + createRowURL(1) );
alert( "row2: " + createRowURL(2) );
$("#mydiv").load("<%=renderURL.toString()%>");
alert(data);
}
});
}
function createRowURL( row ) {
var portletURL = new Liferay.PortletURL();
portletURL.setParameter("rowNumber", row );
return portletURL.toString();
}
function createRenderURL(str) {
alert("");
var renderURL = Liferay.PortletURL.createRenderURL();
alert("hi");
renderURL .setParameter("jspPage",str);
renderURL .setPortletId("eMenuAdvertise_WAR_eMenuAdvertiseportlet");
// i.e. your-unique-portlet-id can be like "helloworld_WAR_helloworldportlet"
}
</script>
<nav>
<div id="jCrumbs" class="breadCrumb module">
<ul>
<li><i class="icon-home"></i></li>
<li>Reseller</li>
<li>Restaurants</li>
</ul>
</div>
</nav>
<div class="row-fluid">
<div class="span12">
<div id="successMsg" style='display:none;' class="alert alert-success"></div>
<div id="errorMsg" style='display:none;' class="alert alert-error"></div>
<h3 class="heading">
Statistics
</h3>
<%String restId = request.getParameter("hide1");%>
<portlet:actionURL name="generateReport" var="reportURL"></portlet:actionURL>
</div>
<div class="">
<div class="">
<div class="">
<div style="float: right">
<p>
<label style="width: 100px"><b>Campaign</b></label>
</p>
<select id="camp_id" name="camp_id"
data-placeholder="- Select Restaurants -" class="chzn-select"
multiple><%
String status = null;
List<campaign> camp_listObj;
if(isReseller)
{
camp_listObj= campaignLocalServiceUtil.getAllCampaignByOrganizations(themeDisplay);
}
else
{
camp_listObj = campaignLocalServiceUtil.getAllCampaignByOrganizationId(themeDisplay);
}
for (int i = 0; i < camp_listObj.size(); i++) {
%>
<option value=<%=camp_listObj.get(i).getPrimaryKey()%>><%=camp_listObj.get(i).getName().toString()%></option>
<%
}
%>
</select>
</div>
<div style="float: left;">
<p>
<button onclick="update_rest('<%=addToDo%>');" class="btn btn-success">GenerateReports</button>
</p>
<b>Start Date</b> <input type="text" style="width: 100px"
id="Start_validBeforeDatepicker" name="validTodayDatepicker"
readonly="true"> <b>End Date</b> <input type="text"
readonly="true" style="width: 100px" id="End_validAfterDatepicker"
name="validAfterDatePicker">
</div>
</div>
</div>
<div style="visibility: hidden;">
<input type="hidden" name="report_path" id="report_path" value="">
</div>
<%
System.setProperty("java.awt.headless", "true");
System.out.println(java.awt.GraphicsEnvironment.isHeadless());
%>
</div>
</div>
<div class="bordercolor" id="mydiv">
</div>
<script type="text/javascript">
function editrestaurant(id){
$(".span12").html("<img class='ajax-loader' src='<%=loading_img_path%>'/>");
$.ajax({
type:'post',
url:'<%=editrestURL.toString()%>',
data:{restId:id},
success:function(data){
$(".main_content").html(data);
}
});
}
function newrestaurant(){
$(".span12").html("<img class='ajax-loader' src='<%=loading_img_path%>'/>");
$.ajax({
type:'post',
url:'<%=ajaxaddnewrestURL.toString() %>',
data:{},
success:function(data){
$(".main_content").html(data);
}
});
}
</script>
portlet.vm
#set ($portlet_display = $portletDisplay)
#set ($portlet_id = $htmlUtil.escapeAttribute($portlet_display.getId()))
#set ($portlet_title = $portlet_display.getTitle())
#set ($portlet_back_url = $htmlUtil.escapeAttribute($portlet_display.getURLBack()))
<section id="portlet_$portlet_id">
$portlet_display.writeContent($writer)
</section>
portal_normal.vm
#parse ($init)
<html class="#language("lang.dir")" dir="#language("lang.dir")" lang="$w3c_language_id">
<head>
</head>
<body class="$css_class">
<div id="wrapper">
<div id="content">
$theme.wrapPortlet("portlet.vm", $content_include)
</div>
</div>
</body>
$theme.include($bottom_include)
</html>
portal_popup.vm
<!DOCTYPE html>
#parse ($init)
<html dir="#language ("lang.dir")" lang="$w3c_language_id">
<head>
<title>$the_title</title>
$theme.include($top_head_include)
</head>
<body class="portal-popup $css_class">
$theme.include($content_include)
$theme.include($bottom_ext_include)
</body>
</html>
navigation.vm
<nav class="$nav_css_class" id="navigation">
<h1>
<span>#language("navigation")</span>
</h1>
<ul>
#foreach ($nav_item in $nav_items)
#if ($nav_item.isSelected())
<li class="selected">
#else
<li>
#end
<a href="$nav_item.getURL()" $nav_item.getTarget()><span>$nav_item.icon() $nav_item.getName()</span></a>
#if ($nav_item.hasChildren())
<ul class="child-menu">
#foreach ($nav_child in $nav_item.getChildren())
#if ($nav_child.isSelected())
<li class="selected">
#else
<li>
#end
<a href="$nav_child.getURL()" $nav_child.getTarget()>$nav_child.getName()</a>
</li>
#end
</ul>
#end
</li>
#end
</ul>
</nav>
In the <script> you have two javascript functions - createRowURL and createRenderURL which make use of the Alloy UI scripts as follows:
function createRowURL( row ) {
var portletURL = new Liferay.PortletURL(); // this is the line using AUI
portletURL.setParameter("rowNumber", row );
return portletURL.toString();
}
function createRenderURL(str) {
alert("");
var renderURL = Liferay.PortletURL.createRenderURL(); // this is the line using AUI
alert("hi");
renderURL .setParameter("jspPage",str);
renderURL .setPortletId("eMenuAdvertise_WAR_eMenuAdvertiseportlet");
// i.e. your-unique-portlet-id can be like "helloworld_WAR_helloworldportlet"
}
So I would suggest instead of using the <script> ... </script> tag use <aui:script> ... </aui:script> tags (this loads all the AUI and Liferay modules), for using this tag you would need to define the taglib in your jsp like:
<%# taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>`
Edit (after seeing the theme templates):
I can see that in your portal_normal.vm you have removed the following lines from <head> and <body> tags respectively:
$theme.include($top_head_include) <!-- this statement is removed from <head> -->
$theme.include($body_top_include) <!-- this statement is removed from <body> -->
Please include these statements back in the theme templates and your scripts would work. The statement $theme.include($top_head_include) this is responsible to include all the AUI related stuff (javascripts, functions etc) and also some variables in the request attribute.
Note: Please always be careful while removing anything from themes and hooks. You should always know what is the purpose of the statements you are removing or modifying.
Hope this helps.

"The requested resource was not found" When submitting a form in liferay portlet

I'm developing a liferay portlet. This is not my first time doing that, but a get a simple error that I can't understand why I'm getting this error. When I click submit button I get this error
The requested resource was not found. "http://localhost:8081/addProduct"
It's more than hours I'm trying to solve it and I know that I have made a silly mistake. Can any body help me solve this problem? Any help is appreciated in advance. Here is my jsp code:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%# page import="javax.portlet.PortletURL" %>
<portlet:defineObjects />
This is the <b>ServiceBuilderTest</b> portlet.
<portlet:actionURL var="addProduct" name="addProductAction"/>
<aui:form method="post" action="addProduct">
<aui:fieldset>
<aui:input name="productName" label="Product Name"></aui:input>
<aui:input name="userID" label="User ID"></aui:input>
<aui:input name="companyID" label="company ID"></aui:input>
<aui:input name="groupID" label="Group ID"></aui:input>
<aui:input name="serialNumber" label="Serial Number"></aui:input>
<aui:button type="submit" value="Submit"></aui:button>
</aui:fieldset>
</aui:form>
And this is my portlet class code:
public class ServiceBuilderPortlet extends MVCPortlet{
public void addProductAction(ActionRequest actionReauest, ActionResponse actionResponse) throws SystemException, PortalException
{
String productName = actionReauest.getParameter("productName");
String userID = actionReauest.getParameter("userID");
String companyID = actionReauest.getParameter("companyID");
String groupID = actionReauest.getParameter("groupID");
String serialNumber = actionReauest.getParameter("serialNumber");
PRProduct product = PRProductLocalServiceUtil.addProduct(Long.parseLong(companyID), Long.parseLong(groupID), productName,
serialNumber, Long.parseLong(userID));
}
}
make it
<portlet:actionURL var="addProduct" name="addProductAction"/>
<aui:form method="post" action="<%=addProduct%>">
...
actually, I'd see it as best practice to not name the action "addProductAction", but just "addProduct", so the changes would be as such (including one line of java, the rest looks good (visually, not tried/tested):
<portlet:actionURL var="addProduct" name="addProduct"/>
<aui:form method="post" action="<%=addProduct%>">
....
and
public class ServiceBuilderPortlet extends MVCPortlet{
public void addProduct(ActionRequest request, ActionResponse response) throws SystemException, PortalException {
// ...
}
}

Resources