SpringMVC(一)
第一节:SpringMVC简介
SpringMVC 是一套功能强大,性能强悍,使用方便的优秀的 MVC 框架;
在web.xml中配置拦截所有的请求,使用org.springframework.web.servlet.DispatcherServlet转发请求。
spring-mvc.xml 配置视图解析。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMvc01</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <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:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
<?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" 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"> <!-- 使用注解的包,包括子集 ,自动扫描生成bean--> <context:component-scan base-package="com.java1234"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"></property> </bean> </beans>
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloWorldController { @RequestMapping("/helloWorld") public String helloWorld(Model model){ model.addAttribute("message", "StringMvc大爷你好!"); return "helloWorld"; } }
第二章 SpringMVC控制器
第一节:@RequestMapping 请求映射
第二节:@RequestParam请求参数 (默认是true, 如果没有参数就会报错,可以设置成 RequestParam(value="id",required=false))
第三节:ModelAndView返回模型和视图
web.xml and spring-mvc.xml 同上。
@Controller @RequestMapping("/student") public class StudentController { private static List<Student> studentList=new ArrayList<Student>(); static{ studentList.add(new Student(1,"张三",11)); studentList.add(new Student(2,"李四",12)); studentList.add(new Student(3,"王五",13)); } @RequestMapping("/list") public ModelAndView list(){ ModelAndView mav=new ModelAndView(); mav.addObject("studentList", studentList); mav.setViewName("student/list"); return mav; } @RequestMapping("/preSave") public ModelAndView preSave(@RequestParam(value="id",required=false) String id){ ModelAndView mav=new ModelAndView(); if(id!=null){ mav.addObject("student", studentList.get(Integer.parseInt(id)-1)); mav.setViewName("student/update"); }else{ mav.setViewName("student/add"); } return mav; } }
===================list.jsp============== <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="${pageContext.request.contextPath}/student/preSave.do">添加学生</a> <table> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> <c:forEach var="student" items="${studentList }"> <tr> <td>${student.id }</td> <td>${student.name }</td> <td>${student.age }</td> <td><a href="${pageContext.request.contextPath}/student/preSave.do?id=${student.id}">修改</a></td> </tr> </c:forEach> </table> </body> </html> =============add.jsp============================ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="student/save.do" method="post"> <table> <tr> <th colspan="2">学生添加</th> </tr> <tr> <td>姓名</td> <td><input type="text" name="name"/></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age"/></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html> =============update.jsp===================== <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="student/save.do" method="post"> <table> <tr> <th colspan="2">学生修改</th> </tr> <tr> <td>姓名</td> <td><input type="text" name="name" value="${student.name }"/></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age" value="${student.age }"/></td> </tr> <tr> <td colspan="2"> <input type="hidden" name="id" value="${student.id }"/> <input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html> =============index.jsp===================== <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <% response.sendRedirect("student/list.do"); %>
第四节:SpringMVC 对象属性自动封装(表单中的name值和对象的属性一样就会自动封装)
第五节:SpringMVC POST请求乱码解决(使用编码过滤器org.springframework.web.filter.CharacterEncodingFilter对所以的请求)
第六节:Controller内部转发和重定向
请求路径建议使用绝对地址:${pageContext.request.contextPath}/....
重定向: return "redirect:/student/list.do"
转发: return "forward:/student/list.do";(转发可以带数据)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMvc01</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <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>*.do</url-pattern> </filter-mapping> </web-app>
@RequestMapping("/save")
public String save(Student student){
if(student.getId()!=0){
Student s=studentList.get(student.getId()-1);
s.setName(student.getName());
s.setAge(student.getAge());
}else{
studentList.add(student);
}
return "redirect:/student/list.do";
// return "forward:/student/list.do";
}
@RequestMapping("/delete")
public String delete(@RequestParam("id") int id){
studentList.remove(id-1);
return "redirect:/student/list.do";
}
第七节:SpringMvc对Servlet API 的支持
HttpServletRequest ,HttpServletResponse ,HttpSession
第八节:SpringMvc对Json的支持
<!-- 支持对象与json的转换。 -->
<mvc:annotation-driven/>
添加命名空间:xmlns:mvc="http://www.springframework.org/schema/mvc" 及其地址: http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd 及jason.jar包
@ResponseBody 这个注解是把对象转换成jason格式。(建议用原生的ResponseUtil.write(HttpServletResponse response,Object o))
@Controller @RequestMapping("/user") public class UserController { @RequestMapping("/login") public String login(HttpServletRequest request,HttpServletResponse response){ System.out.println("----登录验证---"); String userName=request.getParameter("userName"); String password=request.getParameter("password"); Cookie cookie=new Cookie("user",userName+"-"+password); cookie.setMaxAge(1*60*60*24*7); User currentUser=new User(userName,password); response.addCookie(cookie); HttpSession session=request.getSession(); session.setAttribute("currentUser", currentUser); return "redirect:/main.jsp"; } @RequestMapping("/login2") public String login2(HttpServletRequest request){ return "redirect:/main.jsp"; } @RequestMapping("/login3") public String login3(HttpSession session){ return "redirect:/main.jsp"; } @RequestMapping("/ajax") public @ResponseBody User ajax(){ User user=new User("zhangsan","123"); return user; } } ===================================== public class ResponseUtil { public static void write(HttpServletResponse response,Object o)throws Exception{ response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); out.println(o.toString()); out.flush(); out.close(); } }
<?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: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/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"> <!-- 使用注解的包,包括子集 --> <context:component-scan base-package="com.java1234"/> <!-- 支持对象与json的转换。 --> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"></property> </bean> </beans>
这种比较灵活,使用json-lib jar包把对象转jsonObject 或 list<> 转 jsonArray
/** * 通过任务id获取请假单 * @param taskId * @param response * @return * @throws Exception */ @RequestMapping("/getLeaveByTaskId") public String getLeaveByTaskId(String taskId,HttpServletResponse response)throws Exception{ //通过taskId 和 流程变量名称找到leaveId Integer leaveId=(Integer) taskService.getVariable(taskId, "leaveId"); Leave leave=leaveService.findById(leaveId); JSONObject result=new JSONObject(); result.put("leave", JSONObject.fromObject(leave)); ResponseUtil.write(response, result); return null; } /** * 根据条件分页查询请假单集合 * @param page * @param rows * @param userId * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,String userId,HttpServletResponse response)throws Exception{ PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows)); Map<String,Object> map=new HashMap<String,Object>(); map.put("userId",userId); // 用户名 map.put("start", pageBean.getStart()); map.put("size", pageBean.getPageSize()); List<Leave> leaveList=leaveService.find(map); Long total=leaveService.getTotal(map); JsonConfig jsonConfig=new JsonConfig(); jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss")); JSONObject result=new JSONObject(); JSONArray jsonArray=JSONArray.fromObject(leaveList,jsonConfig); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; }
$.post("${pageContext.request.contextPath}/leave/getLeaveByTaskId.do",{taskId:'${param.taskId}'},function(result){ var leave=result.leave; $("#leavePerson").val(leave.user.firstName+leave.user.lastName); $("#leaveDays").val(leave.leaveDays); $("#leaveReason").val(leave.leaveReason); },"json"); <table id="dg" title="请假管理" class="easyui-datagrid" fitColumns="true" pagination="true" rownumbers="true" url="${pageContext.request.contextPath}/leave/list.do" fit="true" toolbar="#tb"> <thead> <tr> <th field="cb" checkbox="true" align="center"></th> <th field="id" width="30" align="center">编号</th> <th field="leaveDate" width="80" align="center">请假日期</th> <th field="leaveDays" width="30" align="center">请假天数</th> <th field="leaveReason" width="200" align="center">请假原因</th> <th field="state" width="30" align="center">审核状态</th> <th field="processInstanceId" width="30" hidden="true" align="center">流程实例Id</th> <th field="action" width="50" align="center" formatter="formatAction">操作</th> </tr> </thead> </table>
补充:@ModelAttribute


浙公网安备 33010602011771号