Based on SSH Framework-CRM Customer Resource Management System-Simple Small Project Development Record-CRM System-03

Keywords: JSON Java snapshot JSP

I. Editorial staff and the echo of basic information

	@Override
	public CrmStaff findById(String staffId) {
		// TODO Auto-generated method stub
		CrmStaff findStaff = this.getHibernateTemplate().get(CrmStaff.class,staffId);
		return findStaff;
	}

	//Inquiring employees according to id
	@Override
	public CrmStaff findById(String staffId) {
		// TODO Auto-generated method stub
		CrmStaff findStaff = staffDao.findById(staffId);
		return findStaff;
	}

	/* 3 Method 3: Inquire through id first, and compare whether the password is the same or not.
	 * * If not, encrypt the password with MD5
	 * * Data other than OID will be set, all settings
	 * * Cause: The first level cache has been modified, which is inconsistent with the snapshot. By default, when submitted, the update statement is automatically executed.
	 */
	@Override
	public void updateStaff(CrmStaff staff) {
		// TODO Auto-generated method stub
		CrmStaff findStaff = staffDao.findById(staff.getStaffId());
		if(!findStaff.getLoginPwd().equals(staff.getLoginPwd())){
			findStaff.setLoginPwd(MyStringUtils.getMD5Value(staff.getLoginPwd()));
		}
		findStaff.setLoginName(staff.getLoginName());
		findStaff.setStaffName(staff.getStaffName());
		findStaff.setGender(staff.getGender());
		findStaff.setOnDutyDate(staff.getOnDutyDate());
		findStaff.setPost(staff.getPost());
	}

	//Operations before editing staff
	public String editUI(){
		//1. Query employees through id
		CrmStaff findStaff = staffService.findById(staff.getStaffId());
		ActionContext.getContext().getValueStack().push(findStaff);
		
		//Query all departments
		List<CrmDepartment> findAllDepartment = departmentService.findAllDepartment();
		ActionContext.getContext().getValueStack().set("findAllDepartment",findAllDepartment);
		return "editUI";
	}
	
	//Staff editor
	public String editStaff(){
		staffService.updateStaff(staff);
		return "editStaff";
	}
}


2. Remarks of Editorial Staff and Departments and Duties

<s:form namespace = "/" action = "staffAction_editStaff">
	<!-- Hidden domain:Depositing users id -->
	
	<s:hidden name = "staffId" value = "%{staffId}"></s:hidden>
	<table width="88%" border="0" class="emp_table" style="width:80%;">
	 <tr>
	    <td>Login name:</td>
	    <td><s:textfield name="loginName"></s:textfield></td>
	    <td>Password:</td>
	    <td><s:password name="loginPwd" showPassword="true"></s:password> </td>
	  </tr>
	 <tr>
	    <td>Full name:</td>
	    <td><s:textfield name="staffName"></s:textfield></td>
	    <td>Gender:</td>
	    <td>
	    	<s:radio list="{'male','female'}" name="gender"></s:radio>
	    </td>
	  </tr>
	 <tr>
	    <td width="10%">Departments:</td>
	    <td width="20%">
			<s:select list="findAllDepartment" name="post.department.depId" onchange="showPost(this)"
				listKey="depId" listValue="depName"
				headerKey="" headerValue="----please--choose--Choose----"
			>
			</s:select>

	    </td>
	    <td width="8%">Duties:</td>
	    <td width="62%">
			<s:select list="post != null ? post.department.postSet : {}" name="post.postId"
				listKey="postId" listValue="postName"
				headerKey="" headerValue="----please--choose--Choose----"  id="postSelectId"
			></s:select>
	    </td>
	  </tr>
	  <tr>
	    <td width="10%">Entry time:</td>
	    <td width="20%">
	    	<s:date name="onDutyDate" format="yyyy-MM-dd" var="myDate"/>
	    	<s:textfield name="onDutyDate" readonly="true" value="%{#myDate}" onfocus="c.showMoreDay=true;c.show(this);"></s:textfield>
	    </td>
	    <td width="8%"></td>
	    <td width="62%"></td>
	  </tr>
	</table>
</s:form>


Third, the second-tier action of ajax for editors

According to the department, inquire about all the positions under the department:

package com.itheima.crm.post.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.itheima.crm.department.domain.CrmDepartment;
import com.itheima.crm.post.dao.PostDao;
import com.itheima.crm.post.domain.CrmPost;

public class PostDaoImpl extends HibernateDaoSupport implements PostDao {

	@Override
	public List<CrmPost> findAllPostWithDepartment(CrmDepartment department) {
		// TODO Auto-generated method stub
		List<CrmPost> findALLPostWithDepartment=  this.getHibernateTemplate().find("from CrmPost where department = ?",department);
		return findALLPostWithDepartment;
	}

}

package com.itheima.crm.post.service.impl;

import java.util.List;

import com.itheima.crm.department.domain.CrmDepartment;
import com.itheima.crm.post.dao.PostDao;
import com.itheima.crm.post.domain.CrmPost;
import com.itheima.crm.post.service.PostService;

public class PostServiceImpl implements PostService {

	//Injecting PostDao
	private PostDao postDao;
	public void setPostDao(PostDao postDao) {
		this.postDao = postDao;
	}
	@Override
	public List<CrmPost> findAllPostWithDepartment(CrmDepartment department) {
		// TODO Auto-generated method stub
		return postDao.findAllPostWithDepartment(department);
	}

}

	//Change all positions in the department according to department inquiries (ajax secondary action in editing)
	//TODO:ajax secondary operation problem (solved)
	public String findAllPostWithDepartment() throws IOException{
		//1 query
		List<CrmPost> findAllPostWithDepartment = this.postService.findAllPostWithDepartment(post.getDepartment());
		
		//2. Converting java objects to json data
		
		//2.1 Exclude unnecessary data
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(new String[]{"department","staffSet"});
		
		//2.2 conversion
		String jsonData = JSONArray.fromObject(findAllPostWithDepartment,jsonConfig).toString();
		
		//3 Send json data to browser
		//3.1 Response to Chinese Scrambling
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		//3.2 send
		ServletActionContext.getResponse().getWriter().print(jsonData);
		
		return "none";
	}

ajax implementation:

	<script type="text/javascript">
		function showPost(obj){
			//1. get department id
			var depId = obj.value;
		
			//2. Send ajax for job search through Department
			
			//2.1 get the ajax engine.
			var xmlHttpRequest =  null;
			if(window.XMLHttpRequest){
				xmlHttpRequest = new XMLHttpRequest();
			}else if(window.ActiveXObject){
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			//2.2 Setting callback function
			xmlHttpRequest.onreadystatechange = function(){
				//Request completed, normal response
				if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
					//3. Get the json data string
					var textData = xmlHttpRequest.responseText;
			
					//3.1 Converting json data strings to json objects
					var jsonData = eval("("+textData+")");
					
					//Get the select element object
					var postSelectElement = document.getElementById("postSelectId");
					postSelectElement.innerHTML = ("<option value = ''>----please--choose--Choose----</option>");
					//3.2 traversal
					for(var i = 0;i<jsonData.length;i++){
						var jsonObj = jsonData[i];
						var postId = jsonObj.postId;
						var postName = jsonObj.postName;
						
						//3.3 Display data to select tag
						postSelectElement.innerHTML += ("<option value = '"+postId+"'>"+postName+"</option>");
					}
					
				}
			}
			//2.3 establish links
			var url = "${pageContext.request.contextPath}/postAction_findAllPostWithDepartment?department.depId="+depId;
			xmlHttpRequest.open("GET", url);
			//2.4 send request
			xmlHttpRequest.send(null);
		}
	</script>

Note: JSON data conversion to strings requires json-lib tools!

API:

JavaBean or Map :JsonObject.fromObject(...).toString()

List or Array:JsonArray.fromObject(...).toString()


Ajax receives Json data strings:

var textData = new XMLHttpRequest().responseText()

Json Data String to Json Object

var jsonData = eval("("+textDate+")")

Fourth, all the queries for the course categories (this is relatively simple, no code is attached here).

5. Conditional Query of Course Categories (***)

//2. All conditional queries
@Override
	public List<CrmCourseType> findCourseTypeWithCondition(String condition,Object[] params) {
		// TODO Auto-generated method stub
		String hql = "from CrmCourseType where 1 = 1" + condition;
		return this.getHibernateTemplate().find(hql, params);
	}

	@Override
	public List<CrmCourseType> findAllCourseWithCondition(CrmCourseType courseType) {
		// TODO Auto-generated method stub
		//1.1 Split Query Conditions
		StringBuilder sb = new StringBuilder();
	
		//1.2 Put together actual parameters, repeatable, sequential
		List<Object> paramsList = new ArrayList<Object>();
		
		//2. filtration conditions
		//2.1 course categories
		if(StringUtils.isNotBlank(courseType.getCourseName())){
			sb.append("and courseName like ?");
			paramsList.add("%"+courseType.getCourseName()+"%");
		}
		//2.2 Course Introduction
		if(StringUtils.isNotBlank(courseType.getRemark())){
			sb.append("and remark like ?");
			paramsList.add("%"+courseType.getRemark()+"%");
		}
		//2.3 total hours
		if(StringUtils.isNotBlank(courseType.getTotalStart())){
			sb.append("and total >= ?");
			paramsList.add(Integer.parseInt(courseType.getTotalStart()));
		}
		
		if(StringUtils.isNotBlank(courseType.getTotalEnd())){
			sb.append("and total <= ?");
			paramsList.add(Integer.parseInt(courseType.getTotalEnd()));
		}
		//2.4 course fees
		if(StringUtils.isNotBlank(courseType.getCourseCostStart())){
			sb.append("and courseCost >= ?");
			paramsList.add(Double.parseDouble(courseType.getCourseCostStart()));
		}
		
		if(StringUtils.isNotBlank(courseType.getCourseCostEnd())){
			sb.append("and courseCost <= ?");
			paramsList.add(Double.parseDouble(courseType.getCourseCostEnd()));
		}
		
		//3. use
		//condition
		String condition = sb.toString();//and...?and...?
		//Actual parameters
		Object[] params = paramsList.toArray();
		
		List<CrmCourseType> findCourseTypeWithCondition = courseTypeDao.findCourseTypeWithCondition(condition, params);
		return findCourseTypeWithCondition;
	}

	public String findAllCourseType(){
		/*//Query all course categories
		List<CrmCourseType> findAllCourseType = this.courseTypeService.findAllCourseType();
		ActionContext.getContext().getValueStack().set("findAllCourseType", findAllCourseType);*/
		
		//All conditional queries
		List<CrmCourseType> findAllCourseType = this.courseTypeService.findAllCourseWithCondition(courseType);
		ActionContext.getContext().getValueStack().set("findAllCourseType", findAllCourseType);
		return "findAllCourseType";
	}
Note: Conditional query is all queries, all queries with conditions!


6. Addition or Updating of Course Categories

Add or update: savaOrUpdate()!

The dao layer requires two methods:

	@Override
	public CrmCourseType findById(String courseTypeId) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(CrmCourseType.class,courseTypeId);
	}
	
	@Override
	public void saveOrUpdate(CrmCourseType courseType) {
		// TODO Auto-generated method stub
		
		this.getHibernateTemplate().saveOrUpdate(courseType);
	}

The service layer requires two methods:

	@Override
	public CrmCourseType findById(String courseTypeId) {
		// TODO Auto-generated method stub
		return courseTypeDao.findById(courseTypeId);
	}
	@Override
	public void addOrEdit(CrmCourseType courseType) {
		// TODO Auto-generated method stub
		courseTypeDao.saveOrUpdate(courseType);
		
	}


The web tier requires two approaches:

	/**
	 * Add or edit display jsp pages
	 * @return
	 */
	public String addOrEditUI(){
		//If an id is an editor, the editor needs to query for details.
		if(StringUtils.isNotBlank(this.courseType.getCourseTypeId())){
			//Press the details of the query into the top of the stack to facilitate automatic tag display
			CrmCourseType findCourseType = this.courseTypeService.findById(this.courseType.getCourseTypeId());
			ActionContext.getContext().getValueStack().push(findCourseType);
		}
		
		return "addOrEditUI";
	}
	
	/**
	 * Add or edit functionality
	 * @return
	 */
	public String addOrEdit(){
		this.courseTypeService.addOrEdit(courseType);
		return "addOrEdit";
	}
Notes on the jsp page:


	  	<td width="11%" align="center">
	  		<s:a namespace="/" action="courseTypeAction_addOrEditUI">
	  			<s:param name="courseTypeId" value="courseTypeId"></s:param>
		       	<img src="${pageContext.request.contextPath}/images/button/modify.gif" class="img" />
	    	</s:a>
	  	</td>
(Edit with a parameter! )

Click Add or Edit to enter this page, but the edited data will be echoed! All dao layers have a method of querying objects according to id. The object is pushed onto the top of the stack in Action, so that the content can be automatically displayed when editing.



The source code for the add or edit page:

<s:form namespace = "/" action = "courseTypeAction_addOrEdit">
	
	<!-- Hidden domain:If there is a value,That is to say, it will not be displayed until it is updated. -->
	<s:if test="courseTypeId != null">
		<s:hidden name="courseTypeId" value="%{courseTypeId}"></s:hidden>
	</s:if>
	<table width="88%" border="0" class="emp_table" style="width:80%;">
	  <tr>
	    <td width="10%">Course categories:</td>
	    <td width="20%"><s:textfield name = "courseName"></s:textfield></td>
	    <td width="8%">Total hours:</td>
	    <td width="62%"><s:textfield name = "total"></s:textfield></td>
	  </tr>
	  <tr>
	    <td>Course fees:</td>
	    <td><s:textfield name = "courseCost"></s:textfield></td>
	    <td></td>
	    <td></td>
	  </tr>
	  <tr>
	    <td>Course Description:</td>
	    <td> </td>
	    <td> </td>
	    <td> </td>
	  </tr>
	  <tr>
	    <td colspan="4"><s:textarea name = "remark" cols = "60" rows = "10"></s:textarea></td>
	  </tr>
	</table>
	
</s:form>
The part of hidden domain is a part that needs to be paid attention to! uuuuuuuuuu

Hidden domains in page source code will not be displayed by clicking Add:

Click Edit:


Because adding and editing go to the same page, the same action, editing links maintain an id, adding links do not exist, so action needs a method to determine whether the ID exists, if the ID exists, according to the ID query and stack after struts to edit the page, data echo, and the page source code hidden. The ID value appears in the Tibetan domain. If there is no id, I don't need to query and display the added page directly without stacking. There is no hidden domain of source code for the corresponding page. Fill in the data, click save, and go to addOrEdit.action. Execute the saveOrUpdate method in the action. Because the hibernate level cache is modified inconsistently with the snapshot, it will change automatically. Data in the database!

Posted by Hardwarez on Mon, 10 Dec 2018 20:03:09 -0800