Controller层
@Controller
表明某类是一个controller控制器,xxx-servlet.xml文件里写有扫描语句来扫描指定包,在指定包中找到标有@Controller的类,xxx-servlet.xml文件会将web.xml中拦截的query请求送到Controller层中标有@Controller注解的类进行匹配。
@RequestMapping
用于请求与controller类、方法匹配使用
写法:写在@Controller与定义类中间
@Controller
@RequestMapping
(
"/student.do"
)
public
class
StudentController{
@RequestMapping
(params =
"method=add"
)
public
String add(HttpServletRequest request, ModelMap modelMap)
throws
Exception{
return
"student_add"
;
}
}
调用add()的js方法
function add(){
window.location.href="<%=request.getContextPath() %>/student.do?method=add";
}
@RequestParam
在SpringMVC后台Controller控制层获取前台页面参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取
例:
Controller层:
@RequestMapping("testRequestParam")
public String filesUpload(@RequestParam String inputStr, HttpServletRequest request) {
System.out.println(inputStr);
int inputInt = Integer.valueOf(request.getParameter("inputInt"));
System.out.println(inputInt);
// ......省略
return "index";
}
前端:
<form action="/gadget/testRequestParam" method="post">
参数inputStr:<input type="text" name="inputStr">
参数intputInt:<input type="text" name="inputInt">
</form>
测试:
执行结果: test1 123
@Autowired
(在Dao层与Service层也使用了该注解)
可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。
自我总结: @Autowired注解主要使用在定义自己写得Service与dao方法,但在实体类中并不需要使用。
用法例controller层:
public class StudentController{ protected final transient Log log = LogFactory.getLog(StudentController.class); @Autowired public StudentService studentService; //........方法体}
用法例dao层:
public class EntityDao { @Autowired private SessionFactory sessionFactory; //........方法体 }
用法例Service层:
public class StudentService { @Autowired public EntityDao entityDao; //........方法体 }
Dao层
@Repository
@Repository对应数据访问层Bean,按编写规范而言就是用来标注Dao层的说明类型注解,与@Controller平级用法也相同.
将@Repository写在Dao类上一行后 xxx-servlet.xml文件通过扫描语句来扫描指定包从而加快扫描速度.
写法: @Repository 或 @Repository("userDao") 或 @Repository( value="userDao")
@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。
用法实例:
@Repository("entityDao")public class EntityDao { //.......方法体}