一、配置好了以后,开始写controller文件
二、时间的注解配置,这样在向页面发送的时候就可以全部都格式化了,方法里面直接加上这个方法即可,想了解更多直接baidu吧。
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
三、基本
1、简单的跳转页面
@Controller //类上面加的,关联到xml文件
public class springM { //因为是注解了,所以就不用继承了
@RequestMapping("/toLogin.do") //注解如何进入这个方法,jsp里:href="toLogin.do",或是浏览器 xx/toLogin.do即可
public String toLogin(){
return "login"; //前后缀已经在配置文件里面了,这里String是路径,这里的意思是跳转到了login.jsp页面
}
ModelAndView
ModelAndView mv=new ModelAndView("error.jsp");//返回的界面
mv.addObject("",xx);
view
可以返回excel,pdf什么的,不常用
map
就是直接返回map集合
2、response重定向到其他controller
@RequestMapping("/redirectTo.do")
public String redirectTo(){
return "redirect:/test1/toForm.do"; //test1是类路径,如果是不是本类才用,注意“/”
}
3、参数
//person是个对象,有get/set方法,只要传的参数和person的属性一一对应,就不用set进属性了,会自动set进去
这里也可以是两个对象,传过来的参数也会注入到第二个对象中
@RequestMapping("/toPerson.do")
public String toPerson6(Model model,Person person) throws Exception{
//Person person = new Person();
……………………
//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//Date date = format.parse("1985-04-22");
//person.setBirthday(date); //时间写错了,也会自动计算的
model.addAttribute("p", person);//放入request中,p就是name,person就是key(对象\数据)
return "index";
}
4、ajax
jsp页面:普通的ajax即可,注意url是:login.do ,因为前后缀都已经有了,这里就不用“/”了
@RequestMapping("/ajax.do")
public void login(String name,PrintWriter out){ //这里这样就是最简单易懂的写法,也是推荐的写法
String result=name+"先生";
out.write(result);
}
5、表单(文件上传)
①配置文件,两句话即可
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400"></property>
</bean>
②方法
@RequestMapping(value="/toPerson.do")
public String toPerson(Person person,HttpServletRequest request) throws Exception{
//第一步转化request
MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
//获得文件
CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
//获得文件的字节数组(文件转二进制)
byte[] bfile = cfile.getBytes();
//拿到项目的部署路径
String path = request.getSession().getServletContext().getRealPath("/");
//定义文件的输出流
OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName));//fileName自己起名字
out.write(bfile);
out.flush();
out.close();
return "jsp1/index";
}