SpringMVC
- SpringMVC结构图
-
创建webproject
-
直接使用maven提供的web.app模板創建
项目结构图:
1545531860484.png
-
-
编写web.xml,在其中注册一个特殊的servlet,前端控制器
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Spring_Mvc</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <!--urlpattern写/ 不要写/*--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
-
编写一个SpringMvc的配置文件
-
注册一个视图解析器 (在web-inf下新建springmvc-servlet.xml文件,该文件供web.xml中的DispatcherServlet注册时查找)
<?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: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-3.1.xsd"> <!--用以查找jsp文件:/jsp文件夹下的以.jsp结尾的文件--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前綴--> <property name="prefix" value="/jsp/"></property> <!--後綴--> <property name="suffix" value=".jsp"></property> </bean> <!--配置注解扫描文件--> <context:component-scan base-package="com.zakl.controller"></context:component-scan> <bean class="com.zakl.controller.HelloController" name="/helloController" ></bean> </beans>
-
4.编写控制器(注意将返回视图放置与webapp下的jsp文件夹中,如果直接放在在根目录下,则setViewName("/mygirl.jsp"))
//controller 只具有一个方法的接口成为函数式接口
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mav=new ModelAndView();
mav.addObject("girl","linda");
mav.setViewName("mygirl");
return mav;
}
},
/* 基于注解模式-- 需要在springmvc-servlet.xml中注册扫描bean,该种实现比以上方法更简便 */
@Controller //标记为spring的一个组件,并且是控制器的组件,此时handlermappong会去扫描这个controller是否与之匹配,匹配成功就将工作交予该controller,匹配原则通过@RequestMapping(URI)进行匹配
public class ByeController {
@RequestMapping("/bbbb")
public String method(Model model){
model.addAttribute("model","李荣浩");
return "bye";
}
}
<context:component-scan base-package="com.zakl.controller"></context:component-scan>
/*基于注解模式 --无需再springmvc.servlet.xml中注册component-sacn 但是需要注册controller Bean*/
<bean class="com.zakl.controller.ByeController" ></bean>
@Controller
public class ByeController {
@RequestMapping("/aa")
public String bye(Model model){
model.addAttribute("model","李荣浩");
return "bye";//返回的string就是逻辑视图名称 bye.jsp
}
//访问路径aa
//为什么可以成功,我都唔知。。。
5.返回视图
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
this is my girl: ${girl}
</body>
</html>
Springmvc-servlet.xml配置位置:
DispatcerSerlvet默认查找web-inf下的springmvc-servlet.xml文件[图片上传失败...(image-ebf666-1545553656872)]
可以通过<init-param>标签更改位置满足maven项目式结构开发:
<servlet>
<!--[<servlet-name>]-servlet =namespace
默认为在web-inf下查找namespace(springmvc-servlet).xml文件
-->
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<!-- 该种配置将命名空间更改为mvc = 在web-inf下查找mvc.xml文件
<init-param>
<param-name>namespace</param-name>
<param-value>mvc</param-value>
</init-param>
-->
</servlet>
jsp <c:foreach 遍历>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
转发与重定向
默认的 return 就是一种转发
@RequestMapping("/aa")
public String bye(Model model){
model.addAttribute("model","李荣浩");
return "bye";
}
重定向到页面(注意这里的的return要返回path ,注意以反斜杠表明地址,重定向无法传递当前数据,相当于用户重新发起一次request请求)
@RequestMapping("/redirecttojsp")
public String redirecttojsp(Model model){
System.out.println("重定向");
return "redirect:/index.jsp";
}
转发到控制器forward:控制器声明URI(其中的model数据仍然可以被新的控制器所接收,并最终返回给页面):
@RequestMapping("/forward")
public String forwardtoController(Model model){
model.addAttribute("mmm","1111");
System.out.println("forwardtoController");
return "forward:/Bye/users";
}
springmvc访问web元素
-
request
@Controller @RequestMapping("/test") public class TestController { @RequestMapping("/request") public String getrequest(HttpServletRequest httpServletRequest){ String o=httpServletRequest.getParameter("boy"); System.out.println("输出内容"+o); return null; } } //控制台答应数据为:输出内容wuzerui //浏览器访问路径为:http://localhost:8080/SpringMvc_war_exploded/test/request?boy=wuzerui
-
session
@RequestMapping("/session") public String setsession(HttpSession session){ session.setAttribute("session","hi") session.getServletContext().setAttribute("会话","这是我的会话"); return null; } //可通过另一个test.jsp页面中的${会话},${session},得到数据
application
SpringMVC注解详情
-
路劲数组访问,多路径访问一个controller
@RequestMapping(value=["/uri","/uri2"])
@RequestMapping(path=["/uri","/uri2"])
-
限定请求方式只能为GET(其他方式同理,可以写成数组):
@RequestMapping(method=RequestMethod.GET)
@RequestMapping(path ={"p1","p2"},method= RequestMethod.GET) public String onlyget(){ System.out.println("this is onlygetMethod"); return "test"; }
获取项目的地址:
@WebServlet(urlPatterns = {},loadOnStartup = 2)
public class WebPatInitServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
//在整个应用中上下文使用webpath来存储上下文路径
config.getServletContext().setAttribute("webpath",config.getServletContext().getContextPath());
super.init(config);
}
}
//loadonstartup =2 是为了让这个servlet最快加载,可以优先获取到webpath
表单访问:
<form action="${webpath}/test/p1" method="post" onsubmit="">
<input type="submit">
</form>
<!-- 以前的写法 ------->
<form action="${pageContext.request.contextPath}/test/p1" method="post" onsubmit="">
<input type="submit">
</form>
网友评论