栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC02

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC02

idea创建Web项目的三种方式

方式一:

在idea中创建web项目【便于打war包,让实施人员部署程序工作,推荐使用】

1.新建空的maven项,
2.在main文件夹中添加webapp文件夹,再在webapp文件夹下创建WEB-INF文件夹
3.在WEB-INF文件夹下创建web.xml
4.在project Settings中的Facets项目中添加Web项目
5.在project Settings中的Modules项目中修改Deployment Descriptors的路径为web.xml的路径,修改Web Resource Directories的路径为webapp的路径
注意查看project Settings中的Artifacts项目中WEB-INF/classes下有没有lib目录看看有没有jar包

方式二:

  1. 创建一个空的maven项目【不使用idea自带的骨架】
  2. 右键项目添加web的支持 Add frameworks Support

方式三:
创建一个mavean项目勾选idea自带的骨架【org.apache.maven.archetypes:maven-archetype-webapp】

Ant风格URL
  • Ant 风格资源地址支持 3 种匹配符

    a) ?:匹配一个字符

    b) *:匹配任意字符

    c) **:匹配任意层、任意字符路径

  @RequestMapping("/successful?")
public String testHelloWorld(){
    return "successful";
}

@PathVariable注解
  • 作用:将占位符中参数,注入处理请求方法的形参中,要求参数名一致。
  • 属性
    • value:设置入参参数名 如果只有value属性时,value可以省略不写
    • name:与value作用一致
    • required:设置当前参数是否必须入参
      • true:必须入参,如不入参会报错:500
      • false:不必须入参,如不入参不会报错,会将null值注入
   @RequestMapping("/successful/{id}") //{id}获取浏览器URL中的请求参数 必须和下边方法中的形参名称一致
    public String testHello(@PathVariable(value = "id") Integer id){
        System.out.println("id = " + id);
        return "successful";
    }
REST简介 1 REST与传统URL风格对比
  • 传统CRUD的URL风格
    • 业务 URL 请求方式
    • 增 /addUser POST
    • 删 /deleteUser?id=1001 GET
    • 改 /updateUser POST
    • 查 /getUser?id=1001 GET
  • REST_CRUD的URL风格
    • 业务 URL 请求方式
    • 增 /user POST
    • 删 /user/1001 DELETE
    • 改 /user PUT
    • 查 /user/1001 GET
  • 总结:REST风格CRUD优势
    • 安全!!!因为URL都一样 不知道参数名称 可以防止侵入 传统的URL可以看到参数名称
    • 提高网站排名
    • 便于第三方平台对接
    • HTTP协议底层支持,效率高
2 HiddenHttpMethodFilter源码解析

解决遇到新问题正确思路:第一方【JDK】、第三方、第二方【自己】

  • public static final String DEFAULT_METHOD_PARAM = "_method";
    private String methodParam = DEFAULT_METHOD_PARAM;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
          throws ServletException, IOException {
    
       HttpServletRequest requestToUse = request;
    
       if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
          String paramValue = request.getParameter(this.methodParam);
          if (StringUtils.hasLength(paramValue)) {
             String method = paramValue.toUpperCase(Locale.ENGLISH);
             if (ALLOWED_METHODS.contains(method)) {
                requestToUse = new HttpMethodRequestWrapper(request, method);
             }
          }
       }
    
       filterChain.doFilter(requestToUse, response);
    }
    
    	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
    
    		private final String method;
    
    		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
    			super(request);
    			this.method = method;
    		}
    
    		@Override
    		public String getMethod() {
    			return this.method;
    		}
    	}
    
  • 总结:使用HiddenHttpMethodFilter需要准备如下两步

    - 提交方式必须是:POST
    - 必须提交请求参数:_method

3 HiddenHttpMethodFilter基本使用
  • xml

    
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        HiddenHttpMethodFilter
        
    @RequestMapping(value = "/RestController",method = RequestMethod.PUT)
    public String updateUser(){
        System.out.println("修改User信息...");
        return "success";
    }
    
    
    @RequestMapping(value = "/RestController",method = RequestMethod.DELETE)
    public String deleteUser(){
        System.out.println("删除User信息...");
        return "success";
    }
    
SpringMVC处理请求数据

JavaWeb阶段【Servlet中处理请求数据-request】

  • 获取请求参数
    • request.getParameter()
    • request.getParameterValues()
    • request.getParameterMap()
  • 获取请求头
    • request.getHeader()
  • 获取请求行【请求方式、uri】
    • request.getMethod()
    • request.getRequestURI()
    • request.getRequestURL()
  • request.getcookies():获取cookie信息

1 SpringMVC获取请求参数【重要】
  • 默认情况:当参数名与处理请求方法中形参名一致时,SpringMVC可以实现自动入参 即可以不加@RequestParam注解
  • @RequestParam注解【重要】
    • value:设置入参参数名
    • name:与value属性作用一致
    • required:设置当前参数,是否必须入参
      • true【默认值】:必须入参,如未入参会报错:400
      • false:不必须入参,如未入参,会将null值注入【建议使用包装类】
    • defaultValue:设置默认值
      • 只有未入参,就会为指定参数设置默认值
点击访问successful页面@RequestParam
  @RequestMapping("/successful999")
  public String testHello3(@RequestParam(value ="id", required = true) Integer deptId,@RequestParam(value ="name",
          required = true)String deptName){
      System.out.println("deptId = " + deptId);
      System.out.println("deptName = " + deptName);

      return "successful";
  }
2 SpringMVC使用POJO入参【重要】
  • 必须要保证请求参数名与POJO的属性名保持一致。支持级联属性入参

  • 示例

    添加员工信息

    员工id:
    员工姓名:
    员工薪资:
    员工部门ID:
    员工部门名称:
    @RequestMapping("/addEmp")
    public String addEmp(Emp emp){
        System.out.println("emp = " + emp);
        return "success";
    }
    
    public class Emp {
        private Integer empId;
        private String empName;
        private Double salary;
        private Dept dept;
        //....
    }
    public class Dept {
        private Integer id;
        private String deptName;
    	//...
    }
    
3 SpringMVC获取请求头
  • @RequestHeader:获取请求头

    • 属性

      • value:设置获取请求头参数名称
      • name:与value作用一致
      • required:设置当前请求头是否必须入参
        • true【默认值】:必须入参
        • false:不必须入参
      • defaultValue:设置默认值
        • 如有未入参请求头,则设置当前默认值
    • 示例代码

      @RequestMapping("/getRequestHeader")
      public String getHeader(@RequestHeader("User-Agent")String uAgent,
                              @RequestHeader("Referer")String referer,
                              @RequestHeader(value = "cookie",required = false)String cookie){
          System.out.println("uAgent = " + uAgent);
          System.out.println("referer = " + referer);
          System.out.println("cookie = " + cookie);
          return "success";
      }
      
4 SpringMVC获取cookievalue
  • @cookievalue

    • 属性
      • value:设置获取cookievalue参数名称
      • name:与value作用一致
      • required:设置当前cookievalue是否必须入参
        • true【默认值】:必须入参
        • false:不必须入参
      • defaultValue:设置默认值
        • 如有未入参cookievalue,则设置当前默认值
  • 示例代码

    @RequestMapping("/getcookievalue")
    public String getcookievalue(HttpServletRequest request, @cookievalue(value = "JSESSIONID",required = false)String cValue){
        HttpSession session = request.getSession();
        System.out.println("sessionId:" + cValue);
        return "success";
    }
    
5 SpringMVC中支持原生Servlet中API
  • 如需要原生Servlet底层API,直接将对象入参即可
@RequestMapping("/getcookievalue")
    public String getcookievalue(HttpServletRequest request,
                                HttpSession session,
                                 @cookievalue(value = "JSESSIONID",required = false)String cValue){
//        HttpSession session = request.getSession();
//        System.out.println("sessionId:" + cValue);
        String id = session.getId();
        System.out.println("id = " + id);
        return "success";
    }
SpringMVC中解决【请求与响应】乱码问题

JavaWeb中如何解决乱码问题

request.setCharacterEncoding(“UTF-8”);

response.setContentType(“text/html;charset=UTF-8”);

1 源码解析
@Nullable
	private String encoding;

	private boolean forceRequestEncoding = false;

	private boolean forceResponseEncoding = false;

    public void setForceEncoding(boolean forceEncoding) {
       this.forceRequestEncoding = forceEncoding;
       this.forceResponseEncoding = forceEncoding;
    }

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String encoding = getEncoding();
		if (encoding != null) {
			if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
				request.setCharacterEncoding(encoding);
			}
			if (isForceResponseEncoding()) {
				response.setCharacterEncoding(encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

2 示例代码

    CharacterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
        forceEncoding
        true
    
    
        encoding
        UTF-8
    


    CharacterEncodingFilter
    
   @Nullable
   //视图对象
   private Object view;

   
   @Nullable
   //数据模型
   private ModelMap model;
   
   
   
   public void setViewName(@Nullable String viewName) {
		this.view = viewName;
	}
	public String getViewName() {
		return (this.view instanceof String ? (String) this.view : null);
	}
	
    
    public Map getModel() {
		return getModelMap();
	}
    public ModelMap getModelMap() {
		if (this.model == null) {
			this.model = new ModelMap();
		}
		return this.model;
	}
    protected Map getModelInternal() {
		return this.model;
	}
    
    
    public ModelAndView addObject(Object attributevalue) {
		getModelMap().addAttribute(attributevalue);
		return this;
	}
    public ModelAndView addObject(String attributeName, @Nullable Object attributevalue) 	{
		getModelMap().addAttribute(attributeName, attributevalue);
		return this;
	}
   
}
3 使用ModelAndView作为方法返回值,处理响应数据【示例代码】
@RequestMapping("/responsedata")
public ModelAndView testResponseData(){
    ModelAndView mv = new ModelAndView();
    //为mv设置数据模型
    mv.addObject("deptId",1001);
    mv.addObject("deptName","秘书部门");
    //为mv设置视图对象
    mv.setViewName("success");
    return mv;
}
4使用Model或Map或ModelMap作为方法参数入参,处理响应数据【示例代码】
    @RequestMapping("/responsedataMap")
    public String testresponseDataMap(Model model){

        //将数据共享域中【map】
        Emp emp = new Emp();
        emp.setEmpId(101);
        emp.setEmpName("康江");
        emp.setSalary(15000.0);
        emp.setDept(new Dept(1001,"研发部门"));

//        map.put("emp",emp);
        model.addAttribute("emp",emp);

        return "success";
    }

html获取响应数据

员工信息


员工id:
员工姓名:
员工薪资:
员工所属部门id:
员工所属部门名称:
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/332350.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号