SSM integrated detailed teaching (below)
5. SSM integrated page development
1 Preparations
In order to ensure that static resources can be accessed, static resource filtering needs to be set
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**")
.addResourceLocations("/pages/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**")
.addResourceLocations("/plugins/");
}
}
2 list query function
- front-end code
//列表
getAll() {
//发送ajax请求
axios.get("/books").then((res)=>{
this.dataList = res.data.data;
});
}
3 Add function
- front-end code
//弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
//重置表单
resetForm() {
this.formData = {
};
},
//添加
handleAdd () {
//发送ajax请求
axios.post("/books",this.formData).then((res)=>{
console.log(res.data);
//如果操作成功,关闭弹层,显示数据
if(res.data.code == 20011){
this.dialogFormVisible = false;
this.$message.success("添加成功");
}else if(res.data.code == 20010){
this.$message.error("添加失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
},
- Code-behind improvements
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
//增删改的方法判断了影响的行数是否大于0,而不是固定返回true
public boolean save(Book book) {
return bookDao.save(book) > 0;
}
//增删改的方法判断了影响的行数是否大于0,而不是固定返回true
public boolean update(Book book) {
return bookDao.update(book) > 0;
}
//增删改的方法判断了影响的行数是否大于0,而不是固定返回true
public boolean delete(Integer id) {
return bookDao.delete(id) > 0;
}
public Book getById(Integer id) {
if(id < 0){
throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
return bookDao.getById(id);
}
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
4 Modification function
- Display pop-up box to query book information
//弹出编辑窗口
handleUpdate(row) {
// console.log(row); //row.id 查询条件
//查询数据,根据id查询
axios.get("/books/"+row.id).then((res)=>{
// console.log(res.data.data);
if(res.data.code == 20041){
//展示弹层,加载数据
this.formData = res.data.data;
this.dialogFormVisible4Edit = true;
}else{
this.$message.error(res.data.msg);
}
});
}
- Save modified book information
//编辑
handleEdit() {
//发送ajax请求
axios.put("/books",this.formData).then((res)=>{
//如果操作成功,关闭弹层,显示数据
if(res.data.code == 20031){
this.dialogFormVisible4Edit = false;
this.$message.success("修改成功");
}else if(res.data.code == 20030){
this.$message.error("修改失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
}
5 delete function
// 删除
handleDelete(row) {
//1.弹出提示框
this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
type:'info'
}).then(()=>{
//2.做删除业务
axios.delete("/books/"+row.id).then((res)=>{
if(res.data.code == 20021){
this.$message.success("删除成功");
}else{
this.$message.error("删除失败");
}
}).finally(()=>{
this.getAll();
});
}).catch(()=>{
//3.取消删除
this.$message.info("取消删除操作");
});
}
6. Interceptor
1 Introduction to Interceptor
problem import
Question 1: Who is the object intercepted by the interceptor?
Question 2: What is the difference between an interceptor and a filter?
1.1 Interceptor concept and function
- Interceptor (Interceptor) is a mechanism for dynamically intercepting method calls, and dynamically intercepts the execution of controller methods in SpringMVC
- effect:
- Execute preset code before and after the specified method call
- Block execution of the original method
- Summary: Enhanced
- Core principle: AOP thought
1.2 The difference between interceptors and filters
- Different ownership: Filter belongs to Servlet technology, Interceptor belongs to SpringMVC technology
- The interception content is different: Filter enhances all access, and Interceptor only enhances SpringMVC access
2 Getting Started Case
problem import
What interface does an interceptor need to implement?
2.1 Interceptor code implementation
[Step 1] Define the interceptor
Method: define a class and implement the HandlerInterceptor interface
@Component //注意当前类必须受Spring容器控制
//定义拦截器类,实现HandlerInterceptor接口
public class ProjectInterceptor implements HandlerInterceptor {
@Override
//原始方法调用前执行的内容
//返回值类型可以拦截控制的执行,true放行,false终止
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle..."+contentType);
return true;
}
@Override
//原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
@Override
//原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
[Step 2] Configure the loading interceptor
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//配置拦截器
registry.addInterceptor(projectInterceptor)
.addPathPatterns("/books","/books/*");
}
}
Use the standard interface WebMvcConfigurer to simplify development (note: strong intrusion)
@Configuration
@ComponentScan({
"com.sun.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor)
.addPathPatterns("/books","/books/*");
}
}
2.2 Interceptor process analysis
3 Interceptor parameters
problem import
The postHandle() and afterCompletion() methods are both executed after the processor method is executed. What is the difference?
3.1 Preprocessing
//原始方法调用前执行的内容
//返回值类型可以拦截控制的执行,true放行,false终止
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle..."+contentType);
return true;
}
-
parameter
- request: request object
- response: response object
- handler: The invoked processor object is essentially a method object, which repackages the Method object in reflection technology
-
Return value
If the return value is false, the intercepted processor will not be executed.
3.2 Post-processing
//原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
- Parameter
modelAndView: If the processor execution is completed and has a return result, you can read the corresponding data and page information and jump
Note: If an exception occurs in the handler method, the method will not be executed
3.3 Processing after completion
//原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
- Parameter
ex: If an exception object occurs during the execution of the processor, it can be handled separately for the exception
Note: This method will execute regardless of whether an exception occurs inside the handler method.
4 Interceptor chain configuration
problem import
What is an interceptor chain?
4.1 Multiple Interceptor Configurations
- Define the second interceptor
@Component
public class ProjectInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...222");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...222");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...222");
}
}
- Configure the second interceptor
@Configuration
@ComponentScan({
"com.itheima.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor)
.addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2)
.addPathPatterns("/books","/books/*");
}
}
4.2 Multiple connector workflow analysis
- When multiple interceptors are configured, an interceptor chain is formed
- The running order of the interceptor chain refers to the order in which the interceptors are added
- When the interception of the original processor occurs in the interceptor, the subsequent interceptors will all terminate
- When the interceptor is interrupted, only the afterCompletion operation configured in the previous interceptor will be run