Spring注解用法

时间:2023-12-13 08:51:50

1. Controller层:@Controller

@Controller
@RequestMapping("/user")//请求localhost:8080/user/****
public class UserController  {
@Autowired   //自动注入,不需要getter()和setter()方法
private UserService userService;
@RequestMapping(value = "/toUser")
public String toVideo() {
return "addUser";//跳转到addUser.jsp
}

@RequestMapping(value = "/getQueryVideoList", method = RequestMethod.POST)
@ResponseBody
//@ResponseBody 将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,
//而是调用适合HttpMessageConverter,将返回值写入输出流。
//post方式请求,封装参数pages,属性分页参数属性
//post方式请求,封装参数userview,属性username,pwd;
//AjaxResult自己封装的返回类,返回类型主要以json为主;
public AjaxResult getQueryVideoList(@ModelAttribute("pages") Pages pages, @ModelAttribute("videoView") UserView videoView){
return AjaxResult.success(pages);
}

@RequestMapping(value = "/saveUser", method=RequestMethod.POST)
//post方式请求,封装参数userview,属性username,pwd;
public ModelAndView saveUser(@ModelAttribute("videoView") UserView userView) {
return new ModelAndView("myspace");//跳转到mysqpce页面
}
}

******注意@ResponseBody写入输出流时可以json的形式输出,比较常用,配合jackson组件用。
******重定向:
1.return "redirect:/user/XXX;
2:return new ModelAndView(new RedirectView(request.getContextPath()+"/user/toUser"));

2. Service层:@Service

@Service("videoService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao videoDao;
}

3. DAO层:@Repository

//该类继承的BaseDao类
@Repository("videoDao")
public class UserDaoImpl extends BaseDao implements UserDao {
public Long saveVideo(User user) {
return (Long) getSqlMapClientTemplate().insert("user.saveUser",user);0;
}
}
//该类继承了SqlMapClientDaoSupport
public class BaseDao extends SqlMapClientDaoSupport {

//只不过@Autowired按byType自动注入,而@Resource默认按byName自动注入罢了
@Resource(name = "sqlMapClient")
private SqlMapClient sqlMapClient;
//在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化//Bean,并装配Bean的属性(依赖注入))。
@PostConstruct
public void initSqlMapClient() {
super.setSqlMapClient(sqlMapClient);
}
}