一、springMvc简介及其架构
模型(Model):负责封装应用的状态,并实现应用的功能。通常分为数据模型和业务逻辑模型,数据模型用来存放业务数据,比如订单信息、用户信息等;而业务逻辑模型包含应用的业务操作,比如订单的添加或者修改等。通常由java开发人员编写程序完成,代码量最多
视图(View):包括jsp,html等,视图通过控制器从模型获得要展示的数据,然后用自己的方式展现给用户,相当于人机交互
控制器(Controller):用来控制应用程序的流程和处理用户所发出的请求,当控制器接收到用户的请求后,会将用户的数据和模型的更新相映射,也就是调用模型来实现用户请求的功能;然后控制器会选择用于响应的视图,把模型更新后的数据展示给用户。
二、RequestMapping(映射请求)
1.标准URL映射
@RequestMapping(value=”xxx”) :它可以定义在方法上,也可以定义在类上,value可以写,也可以不写。如果 value不以“/”开头,springmvc会自动加上
类上的 @RequestMapping可以不用写,此时映射就是方法上的映射2.Ant风格的映射(通配符)
? :通配一个字符
* :通配0个或者多个字符
**:通配0个或者多个路径3、占位符的映射
@RequestMapping(value=“/user/{userId}/{name} ")
请求URL:http://localhost:8080/user/1001/zhangsan.do
这种方式虽然和通配符“*”类似,却比通配符更加强大,占位符除了可以起到通配的作用,最精要的地方是在于它还可以传递参数。
比如:@PathVariable(“userId”) Long id, @PathVariable(“name”)String name获取对应的参数。
注意:@PathVariable(“key”)中的key必须和对应的占位符中的参数名一致,而方法形参的参数名可任意取扫描二维码关注公众号,回复: 4945975 查看本文章如果传递的参数类型和接受参数的形参类型不一致,则会自动转换,如果转换出错(例如:id传了abc字符串,方法形参使用Long来接受参数),则会报400错误(参数列表错误)。
四、限定请求参数的映射
@RequestMapping(value=””,params=””)
params=”userId”:请求参数中必须带有userId
params=”!userId”:请求参数中不能包含userId
params=”userId=1”:请求参数中userId必须为1
params=”userId!=1”:请求参数中userId必须不为1,参数中可以不包含userId
params={“userId”, ”name”}:请求参数中必须有userId,name参数
五、开发环境配置
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
application.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--代表访问的地址/hello --> <!--<bean name="/hello" class="com.shenzhenair.demo.HelloWorldController" ></bean> <bean class="com.shenzhenair.demo.AnnotationController" ></bean>--> <!--开启注解扫描--> <context:component-scan base-package="com.shenzhenair.demo"/> <!--mvc注册注解驱动:例如后端把对象转换成json格式--> <mvc:annotation-driven/> <!--支持对静态资源的处理--> <mvc:default-servlet-handler/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/" ></property> <property name="suffix" value=".jsp"></property> </bean > <!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!--设置文件上传的最大尺寸--> <property name="maxUploadSize" value="5243880" /> <property name="defaultEncoding" value="utf-8"/> </bean> </beans>
1.接收普通的请求参数
@RequestParam(value=””, required=true/false, defaultValue=””)
value:参数名
required:是否必须,默认为true,标示请求参数中必须包含该参数,如果不包含则抛出异常
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果请求中不包含该参数则使用默认值。<fieldset > <legend>用户信息</legend> <form action="/hello/test08" > 姓名:<input type="text" name="name" /><br /> 年龄:<input type="text" name="age" /><br /> 婚否:<input type="checkbox" name="isMarry"/><br /> 薪资:<input type="text" name="income" /><br /> 爱好:<input type="checkbox" name="interests" value="bb" />basketball <input type="checkbox" name="interests" value="fb" />football <input type="checkbox" name="interests" value="vb" />vollyball<br /> <input type="submit" value="提交" /> </form> </fieldset>
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test08") @ResponseStatus(value = HttpStatus.OK) // 不用返回页面视图,只在后台进行处理 public void test08(@RequestParam(value = "name",required = true)String name, @RequestParam(value = "age",required = true)Integer age, @RequestParam(value = "isMarry",required = true)boolean isMarry, @RequestParam(value = "income",defaultValue = "0.00")double income, @RequestParam(value = "interests",defaultValue = "")String[] interests ) throws UnsupportedEncodingException { name = new String(name.getBytes("iso-8859-1"), "utf-8"); StringBuffer sb = new StringBuffer(); sb.append("姓名=" + name).append(", 年龄=" + age).append(", 婚否=" + isMarry) .append(", 收入=" + income).append(", 爱好=【"); for (String interest : interests) { sb.append(interest + ","); } sb.deleteCharAt(sb.toString().length() - 1); sb.append("】"); System.out.println(sb.toString()); //return "demo"; } }
2.接收请求路径中的占位符
@PathVariable(value=”id”)获取占位符中的参数
注意:(value=”id”)不能省访问路径:http://localhost:8080/hello/zhangsan/111
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value="{name}/{id}") public ModelAndView test02(@PathVariable("name") String username,@PathVariable("id") Long id){ ModelAndView mv = new ModelAndView(); System.out.println(username + id); mv.addObject("msg","Restfull风格name="+username+",id="+id); mv.setViewName("/hello.jsp"); return mv; } }
3.接收servlet的内置对象
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test04") public String test04(HttpServletRequest request, HttpServletResponse response, HttpSession session , Model model){ model.addAttribute("msg","SpringMVC的内置对象:request="+request.toString()+", response="+response.toString()+", session="+session.toString() +", 内置对象model"); System.out.println("================"); return "demo"; } }
4.获取cookie
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test06") public String test06(HttpServletRequest request, Model model){ Cookie[] cookies = request.getCookies(); if(null != cookies && cookies.length >= 0){ for (Cookie cookie : cookies) { if(cookie.getName().equals("JSESSIONID")){ model.addAttribute("msg","JSESSIONID="+cookie.getValue()); } } } return "demo"; } @RequestMapping(value = "/test07") public String test06(@CookieValue("JSESSIONID") String CookieValue, Model model){ model.addAttribute("msg","JSESSIONID="+CookieValue); return "demo"; } }
5.对象的绑定
<fieldset > <legend>用户信息</legend> <form action="/hello/test09" > 姓名:<input type="text" name="name" /><br /> 年龄:<input type="text" name="age" /><br /> 婚否:<input type="checkbox" name="isMarry"/><br /> 薪资:<input type="text" name="income" /><br /> 爱好:<input type="checkbox" name="interests" value="bb" />basketball <input type="checkbox" name="interests" value="fb" />football <input type="checkbox" name="interests" value="vb" />vollyball<br /> <input type="submit" value="提交" /> </form> </fieldset>
@Data public class User { private String name; private Integer age; private boolean isMarry; private double income; private String[] interests; }
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test09") @ResponseStatus(value = HttpStatus.OK) // 不用返回页面视图,只在后台进行处理 public void test09(User user) throws UnsupportedEncodingException { System.out.println(user); //return "demo"; } }
6.集合的绑定
如果方法需要接受的list集合,不能够直接在方法中形参中使用List<User>
List的绑定,需要将List对象包装到一个类中才能绑定
要求:表单中input标签的name的值和集合中元素的属性名一致。访问路径:http://localhost:8080/hello/test10?users[0].name=zhangsan&users[0].id=1&users[1].name=lisi&users[1].id=2
@Data public class UserVO { private List<User> users; Private Map<String,Object> maps = new HashMap<>(); }
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test10") public String test10(UserVO users,Model model) { model.addAttribute("msg","users"+ users.getUsers().toString() ); return "demo"; } }
7、JSON:需要用到jackson-annotations-2.5.0.jar jackson-core-2.5.0.jar jackson-databind-2.5.0.jar 三个包
在实际开发过程中,json是最为常见的一种方式,所以springmvc提供了一种更为简便的方式传递数据。
@ResponseBody 是把Controller方法返回值转化为JSON,称为序列化。当一个处理请求的方法标记为@ResponseBody时,表示该方法需要输出其他视图(json、xml),springmvc通过默认的json转化器转化输出
@RequestBody 是把接收到的JSON数据转化为Pojo对象,称为反序列化@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test11") @ResponseBody public List<User> test11() { List<User> users = new ArrayList<>(); for (int i = 0; i < 5; i++) { User user = new User(); user.setAge(1); user.setIncome(2.9); user.setName("tom" + i); user.setMarry(true); user.setInterests(new String[]{"herry","hello"}); users.add(user); } return users; } }
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test12") public String test12(@RequestBody User user ,Model model) { model.addAttribute("msg",user.toString()); return "demo"; } }
8.重定向和转发
@Controller @RequestMapping("/hello") public class ParamController { @RequestMapping(value = "/test14") public String testForward(){ return "forward:/hello/test16?id=1&type=forward"; } @RequestMapping(value = "/test15") public String testRedirect(){ return "redirect:test16?id=2&type=redirect"; } @RequestMapping(value = "/test16") public String testForword(Model model,@RequestParam("id")Long id,@RequestParam("type") String type){ model.addAttribute("msg","转发or重定向:"+type); return "demo"; } }
9.文件上传
@RequestMapping(value = "/test13") public String testUpload(@RequestParam("file")MultipartFile file) throws IOException { if(file != null){ file.transferTo(new File("c:/"+file.getOriginalFilename())); } System.out.println(file.getContentType()); System.out.println(file.getOriginalFilename()); System.out.println(file.getSize()); // System.out.println(file.getInputStream()); InputStream is = null; OutputStream os = null; try { is = file.getInputStream(); os = new FileOutputStream(new File("d:/"+file.getOriginalFilename())); IOUtils.copy(is,os); } catch (IOException e){ e.getStackTrace(); }finally { is.close(); os.close(); } return "redirect:/hello.html"; } /* @Controller @RequestMapping("/upload") public class UploadController { @RequestMapping("uploadPic") public void uploadPic(HttpServletRequest request,String fileName,PrintWriter out){ //把Request强转成多部件请求对象 MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request; //根据文件名称获取文件对象 CommonsMultipartFile cm = (CommonsMultipartFile) mh.getFile(fileName); //获取文件上传流 byte[] fbytes = cm.getBytes(); //文件名称在服务器有可能重复? String newFileName=""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); newFileName = sdf.format(new Date()); Random r = new Random(); for(int i =0 ;i<3;i++){ newFileName=newFileName+r.nextInt(10); } //获取文件扩展名 String originalFilename = cm.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //创建jesy服务器,进行跨服务器上传 Client client = Client.create(); //把文件关联到远程服务器 WebResource resource = client.resource(Commons.PIC_HOST+"/upload/"+newFileName+suffix); //上传 resource.put(String.class, fbytes); //ajax回调函数需要会写写什么东西? //图片需要回显:需要图片完整路径 //数据库保存图片的相对路径. String fullPath = Commons.PIC_HOST+"/upload/"+newFileName+suffix; String relativePath="/upload/"+newFileName+suffix; //{"":"","":""} String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}"; out.print(result); } } */
SpringMVC 全注解开发详情
猜你喜欢
转载自blog.csdn.net/m0_38068812/article/details/85455698
今日推荐
周排行