Javaweb框架 SpringMVC
MVC设计模型:
M model模型,Javabean
V View视图,JSP
C Controller控制器,Servlet
入门案例:
需求:
控制器类
//控制器类
@Controller
public class HelloController {
@RequestMapping(path="/hello")
public String sayhello(){
System.out.println("hello spring mvc");
return "success";
}
}
SpringMVC.xml 配置视图解析器 和 SpringMVC注解支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/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="controller"></context:component-scan>
<!--配置视图解析器,告诉HelloController类中的"success"如何跳转-->
<bean id ="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--开启springmvc注解支持,即开启 -->
<mvc:annotation-driven/>
</beans>
web.xml 配置DispatcherServlet控制器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--设置servlet拦截所有请求-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC
@RequestMapping(path="/hello")注解:用于建立请求URL和处理请求方法之间的对应关系,可以写在类前或方法前
请求参数绑定(将表单数据封装到服务器本地对象):
表单jsp页面:表单name属性的值需要和本地Account类的属性名称相同
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--请求参数绑定--%>
<%--<a href="param/testParam" >请求参数绑定</a>--%>
<form action="/param/saveAccount" method="post">
姓名:<input type="text" name="username"/>
密码:<input type="text" name="password"/>
金额:<input type="text" name="money"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
控制器类:只需要把Account account作为saveAccount函数的输入
package controller;
import domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/saveAccount")
public String saveAccount(Account account){
System.out.println("执行了...");
System.out.println(account);
return "success";
}
}