首先导入所需的jar包,项目目录结构如下:
之后需要配置一下web.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 " version="2.5">
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
然后配置applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.sprmvc.po"></context:component-scan>
<!-- 配置视图解析器 将HelloWorldController中的返回值解析为实际的物理视图 -->
<bean
>
<!-- prefix为前缀,suffix为后缀 -->
<property value="/"></property>
<property value=".jsp"></property>
</bean>
</beans>
下面开始建立实体类User.java:
package com.sprmvc.po;
public class User {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
然后是控制层代码:
package com.sprmvc.po;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloWorldController {
@RequestMapping(value="/hello",method = RequestMethod.GET)
public String printHelloWorld(HttpServletRequest request,User user) {
request.setAttribute("userName", user.getUserName());
request.setAttribute("password", user.getPassword());
return "hello";
}
}
这里的value即访问路径,而return的"hello"通过applicationContext.xml中配置的视图解析器会返回到hello.jsp中
接下来我们建立两个.jsp页面,首先是index.jsp:
<body>
<form method="get" action="hello">
用户名:<input type="text">
密码:<input type="password"><br>
<input type="submit" value="提交">
</form>
</body>
这里的method和action分别与控制层中的method和value的值相对应,即HelloWorldController.java中的第11行。
然后是hello.jsp:
1 <body> 2 <h1>操作成功了</h1> 3 您的用户名为:${userName}<br> 4 您的密码为:${password } 5 </body>
这样只需要将项目加载到tomcat下就可以进行访问了,赶快试试吧。