⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 blogjsptemplate.java

📁 OpenCMS内容管理入门指南
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
        HttpSession session = getRequest().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        
        // logout was successful
        try {
			getResponse().sendRedirect(link("/index.html"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    /**
     * Login the given user, preserving the current project context.
     * 
     * @param User username to login
     * @param Password user's password
     * @return FORMACTION_OK if successful, else FORMACTION_ERROR. If an error occurred
     *         the error message can be retrieved via {@link #getRegisterActionMessage()}
     */
    protected int loginUser(String User, String Password) {
		// now login as the newly added user
		CmsProject curProj = getRequestContext().currentProject();
		try {
			// attempt to login the user
	    	String OU = OU_DEEPTHOUGHTS_REGUSERS + User;
			getCmsObject().loginUser(OU, Password);

            // make sure we have a new session after login for security reasons
	        HttpSession session = getRequest().getSession(false);
            if (session != null) {
                session.invalidate();
            }
            session = getRequest().getSession(true);
			
		} catch (CmsException e) {
			// return error code
			setRegisterActionMessage(e.getLocalizedMessage());
			return FORMACTION_ERROR;
		} finally {
	    	// switch back to original project
	    	getRequestContext().setCurrentProject(curProj);
		}
		
		return FORMACTION_OK;
    }
    
    public String getUserRSSFeedURL() {
		// get feed from user preference
		String feedURL = (String) getRequestContext().currentUser().getAdditionalInfo(RSS_FEED_PARAM);
		// if nothing is set and its not the guest user, then try to read the value
		// from the guest user account
		if (null == feedURL && false == getRequestContext().currentUser().isGuestUser()) {
			try {
				return (String) getCmsObject().readUser(OpenCms.getDefaultUsers().getUserGuest()).getAdditionalInfo(RSS_FEED_PARAM);
			} catch (CmsException e) {
				e.printStackTrace();
			}
		}
		// nothing found on user account or guest account, return a default
		return DEFAULT_RSS_URL;
    }
    
    /**
     * Performs the user registration/add comment actions
     * @return
     */
    public int registerUserAction() {
    	// get the requested action
    	String strAction = getRequest().getParameter("action"); 
    	if (null != strAction) {
    		if (strAction.equals("register")) {
	    		String strUser = getRequest().getParameter("username");
	    		String strPass = getRequest().getParameter("password");
				// attempt to register the user
				try {
					// see if the username already exists
					CmsPrincipal.readPrincipal(getCmsObject(), CmsPrincipal.PRINCIPAL_USER, strUser);
					setRegisterActionMessage("The user '" + strUser 
							+ "' already exists. Please select a different username.");
					
					return FORMACTION_ERROR;
				} catch (CmsException e1) {
					// this is good, it means the username is available
				}
				// get the rest of the account parameters
	    		String strPass2 = getRequest().getParameter("passconfirm");
	    		if (false == strPass2.equals(strPass)) {
					setRegisterActionMessage("Password mis-match, please re-enter the password.<br>");
					return FORMACTION_ERROR;
	    		}
	    		String strFirst = getRequest().getParameter("firstname");
	    		String strLast = getRequest().getParameter("lastname");
	    		String strEMail = getRequest().getParameter("email");
	
	    		try {
	    			// to add the user we must first login using the administrative user we created
	    			getCmsObject().loginUser(USR_DEEPTHOUGHTS_BLOG_ADMIN, USR_DEEPTHOUGHTS_BLOG_ADMIN_PW);
	    			
		            // make sure we have a new session after login for security reasons
			        HttpSession session = getRequest().getSession(false);
		            if (session != null) {
		                session.invalidate();
		            }
		            session = getRequest().getSession(true);
					
					// switch to the offline project
					getCmsObject().getRequestContext().setCurrentProject(getCmsObject().readProject("Offline"));
	
					// add additional user information
					CmsUser newUser = getCmsObject().createUser(OU_DEEPTHOUGHTS_REGUSERS + strUser, 
						strPass, "Web User", new Hashtable());
					newUser.setEmail(strEMail);
					newUser.setFirstname(strFirst);
					newUser.setLastname(strLast);

					// add the RSS Feed
					String strFeed = getRequest().getParameter(RSS_FEED_PARAM);
					Map additionalInfo = new HashMap(1);
					additionalInfo.put("RSS_FEED", strFeed);
					newUser.setAdditionalInfo(additionalInfo);
					
					// add the user to the WebUsers group
					getCmsObject().addUserToGroup(newUser.getName(), 
						OU_DEEPTHOUGHTS_REGUSERS + GRP_DEEPTHOUGHTS_WEBUSERS);
	
					// add the role to the user
					OpenCms.getRoleManager().addUserToRole(getCmsObject(), 
						CmsRole.WORKPLACE_USER, newUser.getName());
					
					// save changes
					getCmsObject().writeUser(newUser);
	
					// switch back to online project
			        getCmsObject().getRequestContext().
			        	setCurrentProject(getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID));
					
					// now login the newly added user
					return loginUser(strUser, strPass);
					
				} catch (CmsException e) {
					e.printStackTrace();
					setRegisterActionMessage(e.getLocalizedMessage());
					
					// make sure to logout the admin user, and revert to Guest
					logout();
					return FORMACTION_ERROR;
				}
    		} else if (strAction.equals("update")) {
    			// update the user
    			CmsUser user = getCmsObject().getRequestContext().currentUser();
    			
				// get the account parameters
	    		String strPass = getRequest().getParameter("password");
	    		String strPass2 = getRequest().getParameter("passconfirm");
	    		if (false == strPass2.equals(strPass)) {
					setRegisterActionMessage("Password mis-match, please re-enter the password.<br>");
					return FORMACTION_ERROR;
	    		}
	    		// update the settings
	    		if (strPass.length()> 0) {
	    			user.setPassword(strPass);
	    		}
	    		user.setFirstname(getRequest().getParameter("firstname"));
	    		user.setLastname(getRequest().getParameter("lastname"));
	    		user.setEmail(getRequest().getParameter("email"));

				String strFeed = getRequest().getParameter("rss");
				Map additionalInfo = new HashMap(1);
				additionalInfo.put(RSS_FEED_PARAM, strFeed);
				user.setAdditionalInfo(additionalInfo);
    		
				// save the user object
				try {
					getCmsObject().writeUser(user);
				} catch (CmsException e) {
					e.printStackTrace();
					setRegisterActionMessage(e.getLocalizedMessage());
					
					return FORMACTION_ERROR;
				}
    		}
    	}
    	// no registration action to take
    	return FORMACTION_SHOWFORM;
    }

    /**
     * Read the comments from the current blog entry
     * @returns nothing
     */
    public void getBlogComments() {
		m_iComments = contentloop(m_iContent, FIELD_COMMENT);
    }
    
    /**
     * See if the current blog entry has comments to be displayed
     * 
     * @return true if entry has more comments, else false
     */
    public boolean hasMoreComments() {
    	if (null == m_iComments) {
    		return false;
    	}
		try {
			return m_iComments.hasMoreContent();
		} catch (JspException e) {
			return false;
		}
    	
    }
    
    /**
     * Returns a field value from the current nested Comments item
     * 
     * @param Fieldname	Fieldname to retrieve content from
     * 
     * @return Field content or empty string ("") if no value for field
     */
    public String getCommentField(String Fieldname) {
    	if (null != m_iComments) {
    		return contentshow(m_iComments, Fieldname);
    	}
    	return NULLSTR;
    }
    
    /**
     * Returns the username of the currently logged on user
     * @return
     */
    public String getCurrentUser() {
    	String strUser = getRequestContext().currentUser().getName();
    	// strip off the Org Unit if it exists
    	return CmsOrganizationalUnit.getSimpleName(strUser);
    }
    
    /**
     * Returns the username that submitted the comment for the current blog entry
     * @return Username as a String
     */
    public String getBlogCommentUser() {
    	String strUser = getCommentField("User");
    	// strip off the Org Unit if it exists
    	return CmsOrganizationalUnit.getSimpleName(strUser);
    }
    
    /**
     * Returns the date that the comment was submitted on
     * @return Date as a String
     */
    public Date getBlogCommentDate() {
    	return CmsJspElFunctions.convertDate(getCommentField("Date"));
    }
    
    /**
     * Utility for formatting a date field according to the specified format string.
     * 
     * @param Date	Date value retrieved from OpenCmsDateTime field
     * @param Format Format patter/string to use
     * @return	String with formatted date
     */
    public static String formatDate(String Date, String Format) {
		java.util.Date date = new java.util.Date(); 
		date.setTime(Long.parseLong(Date));
		return BlogJspTemplate.formatDate(date, Format);
    }

    /**
     * Utility for formatting a date field according to the specified format string.  This 
     * method uses the <code>SimpleDateFormat</code> class for date formatting.
     * 
     * @param Date	Java Date object
     * @param Format Format patter/string to use
     * @return	String with formatted date
     * 
     * @see java.text.SimpleDateFormat
     */
    public static String formatDate(Date date, String Format) {
		SimpleDateFormat sdf = new SimpleDateFormat(Format);
		return sdf.format(date);
    }
    
    /**
     * Utility to determine if a character is an alphanumeric.
     * 
     * @param curChar
     * @return true if character is alpha, else false
     */
    public static boolean isAlpha(char curChar) {
    	return  ((curChar>='a') && (curChar<='z')) ||
    	      ((curChar>='A') && (curChar<='Z')) ||
    	      (curChar==':') || (curChar=='_') || (curChar=='.');
    }

    /**
     * This is a utility method for trimming text to the given size.  If the size
     * limit occurs within a word then the size will be increased to prevent a
     * break within the word. 
     * 
     * @param Text Text to trim
     * @param Size Desired size
     * @return Text trimmed to nearest word break
     */
    public static String trimUp(String Text, int Size) {
    	// skip to next non-alpha to prevent breaking in the middle of a word
    	while (Size < Text.length() && isAlpha(Text.charAt(Size))) {
    		Size++;
    	}
    	return Text.substring(0, Size);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -