赞
踩
MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分
M: Model,模型层,指工程中的JavaBean,作用是处理数据
JavaBean分为两类:
V: View,视图层,指工程中的html或jsp等页面,作用是与用户进行交互,展示数据。
C: Controller,控制层,指工程中的servlet,作用是接收请求和响应浏览器。
MVC的工作流程:
用户通过视图层发送请求到服务器,在服务器中请求被Controller接收,Controller调用相应的Model层处理请求,处理完毕将结果返回到Controller,Controller再根据请求处理的结果找到相应的View视图,渲染数据后最终响应给浏览器。
注:三层架构分为表述层(或表示层)、业务逻辑层、数据访问层,表述层表示前台页面和后台servlet
< dependency >< groupId >org.springframework</ groupId >< artifactId >spring-web</ artifactId >< version >5.0.5.RELEASE</ version ></ dependency >
<!-- 全局参数 -->< context-param >< param-name >contextConfigLocation</ param-name >< param-value >classpath:applicationContext.xml</ param-value ></ context-param ><!--Spring 的监听器 -->< listener >< listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class ></ listener >
通过工具获得应用上下文对象
ApplicationContext applicationContext =WebApplicationContextUtils. getWebApplicationContext (servletContext);Object obj = applicationContext.getBean( "id" );
<!--Spring 坐标 -->< dependency >< groupId >org.springframework</ groupId >< artifactId >spring-context</ artifactId >< version >5.0.5.RELEASE</ version ></ dependency ><!--SpringMVC 坐标 -->< dependency >< groupId >org.springframework</ groupId >< artifactId >spring-webmvc</ artifactId >< version >5.0.5.RELEASE</ version ></ dependency >
<!-- 配置 SpringMVC的前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
- package com.zd.controller;
-
- public class UserController {
- public String save(){
- System.out.println("Cotroller save running....");
- return "success.jsp";
- }
-
- }
- package com.zd.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- @Controller
- public class UserController {
- @RequestMapping("/quick")//quick 映射名称
- public String save(){
- System.out.println("Cotroller save running....");
- return "success.jsp";
- }
-
- }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/beans/spring-context.xsd"> <!-- Controller的组件扫描 --> <context:component-scan base-package="com.zd.controller"/> </beans>
修改web.xml的配置
<!-- 配置 SpringMVC的前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
①从代码层面解析
②
xmlns: context ="http://www.springframework.org/schema/context"xmlns: mvc ="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
< context :component-scan base- package =“com.itheima.controller" />
org.springframework.web.servlet.ViewResolver = org.springframework.web.servlet.view.InternalResourceViewResolver
翻看该解析器源码,可以看到该解析器的默认设置,如下:
REDIRECT_URL_PREFIX = "redirect:" -- 重定向前缀FORWARD_URL_PREFIX = "forward:" -- 转发前缀(默认值)prefix = "" ; -- 视图名称前缀suffix = "" ; -- 视图名称后缀
我们可以通过属性注入的方式修改视图的的前后缀
<!-- 配置内部资源视图解析器 -->< bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" >< property name ="prefix" value ="/WEB-INF/views/" ></ property >< property name ="suffix" value =".jsp" ></ property ></ bean >
2. 返回ModelAndView对象
- package com.zd.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
-
- @Controller
- public class UserController {
- @RequestMapping("/quick2")
- public ModelAndView quickMethod2(){
- //Model:模型 作用封装数据
- //view:视图 作用展示数据
- ModelAndView modelAndView = new ModelAndView();
- //设置模型数据
- modelAndView.addObject("username","itcast");//username=itcast
- //设置视图名称
- modelAndView.setViewName("redirect:index.jsp");
- return modelAndView;
- }
-
- @RequestMapping("/quick3")
- public ModelAndView quickMethod3(ModelAndView modelAndView){
- //设置模型数据
- modelAndView.addObject("username","zdzd");//username=zdzd
- //设置视图名称
- modelAndView.setViewName("redirect:index.jsp");
- return modelAndView;
- }
-
- @RequestMapping("/quick4")
- public String quickMethod4(Model model){
- //设置模型数据
- model.addAttribute("username","博学谷");
- return "success.jsp";
- }
- /*
- 向request域存储数据
- 在进行转发时,往往要向request域中存储数据,在jsp页面中显示,那么Controller中怎样向request域中存储数据呢?
- 通过SpringMVC框架注入的request对象setAttribute()方法设置
- */
- @RequestMapping("/quick5")
- public String quickMethod5(HttpServletRequest request){
- //设置模型数据
- request.setAttribute("username","博学谷");
- return "success.jsp";
- }
-
- @RequestMapping("/quick")
- public String save(){
- System.out.println("Cotroller save running....");
- return "success.jsp";
- }
-
- }
- @RequestMapping("/quick6")
- public void quickMethod6(HttpServletResponse response) throws IOException {
- response.getWriter().print("hello itcast");
- }
- @RequestMapping("/quick7")
- @ResponseBody //告知SpringMVC框架不进行试图跳转 直接进行数据响应
- public String quickMethod7(){
- return "hello zdzd";
- }
在异步项目中,客户端与服务器端往往要进行json格式字符串交互,此时我们可以手动拼接json字符串返回。
添加依赖
<!--jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency>
- @RequestMapping("/quick6")
- @ResponseBody
- public String quickMethod6() throws IOException {
- return "{\"name\":\"zhangsan\",\"age\":18}";//直接返回
- }
使用json的转换工具将对象转换成json格式字符串再返回
- @RequestMapping("/quick9")
- @ResponseBody
- public String quickMethod9() throws JsonProcessingException {
- User user = new User();
- user.setUsername("zhangsan");
- user.setPassword("2346");
- //使用json的转换工具将对象转换成json格式字符串再返回
- ObjectMapper objectMapper = new ObjectMapper();
- String json = objectMapper.writeValueAsString(user);
- return json;
- }
(2)返回对象集合
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--Controller的组件扫描--> <context:component-scan base-package="com.zd"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置内部资源视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- /jsp/success.jsp --> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置处理器映射器--> <!--写了 mvc的注解驱动 可以注释掉了--> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </list> </property> </bean> --> <!--mvc的注解驱动--> <mvc:annotation-driven /> </beans>
- @RequestMapping(value="/quick10")
- @ResponseBody
- //期望SpringMVC自动将User转换成json格式的字符串
- public User save10() throws IOException {
- User user = new User();
- user.setUsername("zhangsan");
- user.setPassword("2346");
- return user;
- }
- @RequestMapping(value="/quick11")
- @ResponseBody //不进行页面跳转
- //返回void代表不进行数据回写
- /*
- 手动输入 quick11?username=zhangsan&password=9876
- 控制台得到:zhangsan 9876
- */
- public void save11(String username,String password) throws IOException {
- System.out.println(username);
- System.out.println(password);
- }
- @RequestMapping(value="/quick12")
- @ResponseBody
- /*
- 输入 quick12?id=11&username=zhangsan&password=9876
- 控制台输出 User{id=11, username='zhangsan', password='9876'}
- */
- public void save12(User user) throws IOException {
- System.out.println(user);
- }
- @RequestMapping(value="/quick13")
- @ResponseBody
- /*
- 输入 quick13?str=111&str=222&str=333
- 控制台输出 [111, 222, 333]
- */
- public void save13(String[] str) throws IOException {
- System.out.println(Arrays.asList(str));//数组直接打印地址,将数组转为集合就可以得到数组中的数据
- }
- package com.zd.domian;
-
- import java.util.List;
-
- public class VO {
-
- private List<User> userList;
-
- public List<User> getUserList() {
- return userList;
- }
-
- public void setUserList(List<User> userList) {
- this.userList = userList;
- }
-
- @Override
- public String toString() {
- return "VO{" +
- "userList=" + userList +
- '}';
- }
- }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/quick14" method="post"> <%--表明是第几个User对象的username password--%> <input type="text" name="userList[0].id"><br/> <input type="text" name="userList[0].username"><br/> <input type="text" name="userList[0].password"><br/> <input type="text" name="userList[1].id"><br/> <input type="text" name="userList[1].username"><br/> <input type="text" name="userList[1].password"><br/> <input type="submit" value="提交"> </form> </body> </html>
- @RequestMapping(value="/quick14")
- @ResponseBody
- /*
- 首先打开 form.jsp进行数据填写提交后
- 控制台输出VO{userList=[User{id=1, username='zhangsan', password='123'}, User{id=2, username='wuzong', password='3435'}]}
- */
- public void save14(VO vo) throws IOException {
- System.out.println(vo);//数组直接打印地址,将数组转为集合就可以得到数组中的数据
- }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <script> var userList = new Array(); userList.push({id:"01",username:"zhangsan",password:"1234"}); userList.push({id:"02",username:"lisi",password:"2345"}); <!-- 发送数据 --> $.ajax({ type:"POST", url:"${pageContext.request.contextPath}/quick15", data:JSON.stringify(userList), <!-- 提交参数 --> contentType:"application/json;charset=utf-8" }); </script> </head> <body> </body> </html>
- @RequestMapping(value="/quick15")
- @ResponseBody
- /*
- 输入ajax.jsp
- 控制台输出 [User{id=1, username='zhangsan', password='1234'}, User{id=2, username='lisi', password='2345'}]
- */
- public void save15(@RequestBody List<User> userList) throws IOException {
- System.out.println(userList);
- }
<!--配置全局过滤的filter--> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- @RequestMapping(value="/quick16")
- @ResponseBody
- /*
- 输入 quick16?name="zhangsan"
- 控制台得到 zhangsan
- 如果不使用@RequestParam注解 输入name=...控制台输出null
- */
- public void save16(@RequestParam(value="name",required = false,defaultValue = "itcast") String username) throws IOException {
- System.out.println(username);
- }
- // localhost:8080/quick17/zhangsan
- //控制台输出 zhangsan
- @RequestMapping(value="/quick17/{name}")
- @ResponseBody
- public void save17(@PathVariable(value="name") String username) throws IOException {
- System.out.println(username);
- }
- package com.zd.converter;
-
- import org.springframework.core.convert.converter.Converter;
-
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
-
- public class DateConverter implements Converter<String, Date> {
- public Date convert(String dateStr) {
- //将日期字符串转换成日期对象 返回
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- Date date = null;
- try {
- date = format.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date;
- }
- }
<!--声明转换器--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.zd.converter.DateConverter"></bean> </list> </property> </bean>
- @RequestMapping(value="/quick18")
- @ResponseBody
- public void save18(Date date) throws IOException {
- System.out.println(date);
- }
- @RequestMapping(value="/quick19")
- @ResponseBody
- public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
- //打印对象地址
- System.out.println(request);//org.apache.catalina.connector.RequestFacade@791e4013
- System.out.println(response);//org.apache.catalina.connector.ResponseFacade@181ed328
- System.out.println(session);//org.apache.catalina.session.StandardSessionFacade@72c1409e
- }
- @RequestMapping(value="/quick20")
- @ResponseBody
- public void save20(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
- System.out.println(user_agent);
- //Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.50
- }
- @RequestMapping(value="/quick21")
- @ResponseBody
- public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
- System.out.println(jsessionId);//7C95C7D9C01BA28DA898959BBAEE231D
- }
upload.jsp 创建一个表单
<form action="${pageContext.request.contextPath}/quick22" method="post" enctype="multipart/form-data"> 名称:<input type="text" name="username"><br> 文件:<input type="file" name="uploadFile"><br> <input type="submit" value="提交"><br> </form>
<!-- fileupload 和 io --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
<!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--上传文件总大小--> <property name="maxUploadSize" value="5242800"/> <!--上传单个文件的大小--> <property name="maxUploadSizePerFile" value="5242800"/> <!--上传文件的编码类型--> <property name="defaultEncoding" value="UTF-8"/> </bean>
- @RequestMapping(value="/quick22")
- @ResponseBody
- public void save22(String username, MultipartFile uploadFile) throws IOException {
- System.out.println(username);//zhangsan
- System.out.println(uploadFile);//org.springframework.web.multipart.commons.CommonsMultipartFile@486df907
- }
- @RequestMapping(value="/quick22")
- @ResponseBody
- public void save22(String username, MultipartFile uploadFile) throws IOException {
- System.out.println(username);//zhangsan
- //获得上传文件的名称,进行保存
- String originalFilename = uploadFile.getOriginalFilename();
- uploadFile.transferTo(new File("D:\\A\\upload\\"+originalFilename));
- }
- @RequestMapping(value="/quick22")
- @ResponseBody
- public void save22(String username, MultipartFile uploadFile1,MultipartFile uploadFile2) throws IOException {
- System.out.println(username);//zhangsan
- //获得上传文件的名称,进行保存
- String originalFilename1 = uploadFile1.getOriginalFilename();
- uploadFile1.transferTo(new File("D:\\A\\upload\\"+originalFilename1));
- String originalFilename2 = uploadFile2.getOriginalFilename();
- uploadFile2.transferTo(new File("D:\\A\\upload\\"+originalFilename2));
- }
- @RequestMapping(value="/quick23")
- @ResponseBody
- public void save23(String username, MultipartFile[] uploadFile) throws IOException {
- System.out.println(username);
- for (MultipartFile multipartFile : uploadFile) {
- String originalFilename = multipartFile.getOriginalFilename();
- multipartFile.transferTo(new File("D:\\A\\upload\\"+originalFilename));
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。