方式一:
在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包
方式二:
- 创建一个空的maven项目【不使用idea自带的骨架】
- 右键项目添加web的支持 Add frameworks Support
方式三:
创建一个mavean项目勾选idea自带的骨架【org.apache.maven.archetypes:maven-archetype-webapp】
-
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协议底层支持,效率高
解决遇到新问题正确思路:第一方【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
-
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"; }
1 SpringMVC获取请求参数【重要】JavaWeb阶段【Servlet中处理请求数据-request】
- 获取请求参数
- request.getParameter()
- request.getParameterValues()
- request.getParameterMap()
- 获取请求头
- request.getHeader()
- 获取请求行【请求方式、uri】
- request.getMethod()
- request.getRequestURI()
- request.getRequestURL()
- request.getcookies():获取cookie信息
…
- 默认情况:当参数名与处理请求方法中形参名一致时,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的属性名保持一致。支持级联属性入参
-
示例
添加员工信息
@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; //... }
-
@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"; }
-
-
@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"; }
- 如需要原生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中解决【请求与响应】乱码问题
1 源码解析JavaWeb中如何解决乱码问题
request.setCharacterEncoding(“UTF-8”);
response.setContentType(“text/html;charset=UTF-8”);
@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 示例代码
3 使用ModelAndView作为方法返回值,处理响应数据【示例代码】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; } }
@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:
员工所属部门名称:



