博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springMVC之annotation优化
阅读量:6978 次
发布时间:2019-06-27

本文共 1932 字,大约阅读时间需要 6 分钟。

 

1.在之前配置的spring配置文件中会有这样的代码:

<!-- 方法映射 -->

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
 <!-- 找类 -->
 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>

这两句是注入开启映射的类。

在spring3.0后有了mvc标签,可以将上两句改为:

<mvc:annotation-driven/>

同样可以达到以上的结果。

2.在controller中我们是这样配置的:

package com.yx.controller.annotation;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller

public class HelloAnnotationController {

 @RequestMapping(value="/user/adduser",method=RequestMethod.GET)

 public ModelAndView addUser(){
  
  return new ModelAndView("/annotationTest","result","add user");
  
 }
 @RequestMapping(value="/user/deluser")
 public ModelAndView delUser(){
  
  return new ModelAndView("/annotationTest","result","delete user");
  
 }

}

这里面也有很多可以优化的:

(1).对于传输方法,在平时开发时没有必要必须规定是什么方法传输,也就是无论get还是post均可以运行。这样只要将“method=RequestMethod.GET”删掉即可。

(2).在没给个方法前面都会出现“/user”即为命名空间,这样代码会太重复。可以在类的前面加上“@RequestMapping("/user2")”

(3).在struts2中方法的返回值一般为String,在springMVC中也可以这样做。

最后controller的代码可以修改为:

package com.yx.controller.annotation;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller

@RequestMapping("/user2")
public class HelloAnnotationController2 {

 @RequestMapping("/adduser")

 public String addUser(HttpServletRequest request){
  request.setAttribute("result","add user 方法");
  return "/annotationTest";
  
 }
 @RequestMapping("/deluser")
 public String delUser(HttpServletRequest request){
  request.setAttribute("result","delete user上述");
  return "/annotationTest";
  
 }

}

 

 

 

转载地址:http://toupl.baihongyu.com/

你可能感兴趣的文章
切版网上线,启用qieban.cn
查看>>
横向ListView(一) ——开篇,基础逻辑实现
查看>>
STM32单片机外部中断配置讲解
查看>>
阿里云智能对话分析服务
查看>>
中文详解phpmailer所有对象和属性
查看>>
python 函数
查看>>
什么是类型别名?什么是潜在类型?
查看>>
Condition
查看>>
10.15 iptables filter表案例
查看>>
Nginx防盗链,Nginx访问控制, Nginx解析php相关配置, Nginx代理
查看>>
芝麻HTTP:Scrapy-Splash的安装
查看>>
专访小邪:从十年技术之路看阿里技术体系的变革
查看>>
python 100例(10)
查看>>
测试服务命名和动态注册路由的方式@Xan
查看>>
如何处理用代码创建SD Sales order时遇到的错误消息KI 180
查看>>
Maven就是这么简单
查看>>
环境变量,cp,mv,查看文档命令
查看>>
usermod命令,用户密码管理和mkpasswd命令
查看>>
HashMap? ConcurrentHashMap? 相信看完这篇没人能难住你!
查看>>
分析PHP中单双引号的误区和双引号小隐患
查看>>