运行控制器方法之前先执行注解@ModelAttribute的方法
1.定义公共父控制类controller
使用注解: @ModelAttribute;
package com.ihrm.common.controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseController
{
protected HttpServletRequest request;
protected HttpServletResponse response;
protected String companyId;
protected String companyName;
@ModelAttribute //进入控制器方法之前执行的方法
public void setResAnReq(HttpServletRequest request,HttpServletResponse response){
this.request=request;
this.response=response;
//以后解决companId = "1"
this.companyId = "1";
this.companyName = "chanzhiboke";
}
}
2.在其它控制类继承该控制类,使用该控制类的属性
package com.ihrm.company.controller;
import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.company.service.CompanyService;
import com.ihrm.company.service.DepartmentService;
import com.ihrm.domain.company.Company;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.company.response.DeptListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//1.解决跨域
@CrossOrigin
@RestController
@RequestMapping(value="/company")
public class DepartmentController extends BaseController
{
@Autowired
private DepartmentService departmentService;
@Autowired
private CompanyService companyService;
/**
* 保存
*/
@RequestMapping(value="/department",method = RequestMethod.POST)
public Result save(@RequestBody Department department){
//1 设置企业id
//String companyId= "1";
department.setCompanyId(companyId);
departmentService.save(department);
return new Result(ResultCode.SUCCESS);
}
/**
* 查询全部[对应企业的全部]
* @return
*/
@RequestMapping(value="/department",method = RequestMethod.GET)
public Result findAll(){
//1 设置企业id
// String companyId= "1";
Company company = companyService.findById(companyId);
List<Department> departmentlist = departmentService.findAll(companyId);
DeptListResult deptListResult = new DeptListResult(company,departmentlist);
return new Result(ResultCode.SUCCESS,deptListResult);
}
/**
* 根据id查询
* @return
*/
@RequestMapping(value="/department/{id}",method = RequestMethod.GET)
public Result findByid(@PathVariable(value="id") String id){
Department byid = departmentService.findByid(id);
return new Result(ResultCode.SUCCESS,byid);
}
/**
* 修改参数
*/
@RequestMapping(value="/department/{id}",method = RequestMethod.PUT)
public Result update(@PathVariable(value="id") String id,@RequestBody Department department){
department.setId(id);
departmentService.update(department);
return new Result(ResultCode.SUCCESS);
}
/**
* 删除数据
*/
@RequestMapping(value="/department/{id}",method = RequestMethod.DELETE)
public Result delete(@PathVariable(value="id") String id,@RequestBody Department department){
departmentService.delete(id);
return new Result(ResultCode.SUCCESS);
}
}