第七章 : Spring MVC教程示例
Posted 墨迹测试
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第七章 : Spring MVC教程示例相关的知识,希望对你有一定的参考价值。
Spring MVC教程通过 DispatcherServlet
提供了一个在Spring框架中使用MVC的优雅解决方案。
在Spring Web MVC中,DispatcherServlet类用作前端控制器。它负责管理spring mvc应用程序的流程。 @Controller
注释用于将类标记为Spring 3中的控制器。 @RequestMapping
注释用于映射请求url。应用于该方法。
Spring Web MVC流程图
如图所示,所有传入请求都被作为前端控制器的 DispatcherServlet
拦截。DispatcherServlet从xml文件中获取处理程序映射的条目,并将请求转发给控制器。控制器返回 ModelAndView
的对象。DispatcherServlet检查xml文件中视图解析器的条目,并调用指定的视图组件。
Spring Web MVC框架示例
创建spring MVC应用程序有7个步骤。步骤如下:
创建请求页面(可选)
创建控制器类
在web.xml文件中提供控制器条目
在xml文件中定义bean
在JSP页面中显示消息
加载spring core和mvc jar文件
启动服务器并部署项目
目录结构
使用Maven的Spring MVC的目录结构
必需的Jar文件或Maven依赖项
要运行此示例,您需要加载:
Spring Core jar文件
Spring Web jar文件
如果您使用的是Maven,则无需添加jar文件。现在,您需要在pom.xml文件中添加maven依赖项。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
1)创建请求页面(可选)
这是一个简单的jsp页面,包含一个链接。它是可选页面。您可以直接调用action类。
index.jsp
<a href="hello.html">click</a>
2)创建控制器类
要创建控制器类,我们使用两个注释 @Controller
和 @RequestMapping
。
该@Controller注解标记这个类作为控制器。
该@RequestMapping注释用于映射具有指定名称的类。
该类返回具有映射名称的 ModelAndView
控制器实例,消息名称和消息值。消息值将显示在jsp页面中。
index.jsp
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC HOW R U";
return new ModelAndView("hellopage", "message", message);
}
}
`在web.xml文件中提供控制器的入口
在这个xml文件中,我们指定了Servlet类DispatcherServlet,它充当Spring Web MVC中的前端控制器。所有对html文件的传入请求都将转发到 DispatcherServlet
。
web.xml
<?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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
4)在xml文件中定义bean
这是我们需要指定ViewResolver和View组件的重要配置文件。
context:component-scan 扫描元素定义了DispatcherServlet搜索控制器类的基本包。
这里, ViewResolver
使用了InternalResourceViewResolver类。
prefix+string returned by controller+suffix 将会被视图组件所调用。
此xml文件应位于WEB-INF目录中。
spring-servlet.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
5)在JSP页面中显示消息
这是一个简单的JSP页面,显示控制器返回的消息。它必须位于 WEB-INF/jsp
目录中。
hellopage.jsp
Message is: ${message}
Output:
Spring 3 MVC多控制器示例
我们可以在Spring Framework中拥有很多控制器类。在这个例子中,我们创建了两个Controller类 HelloWorldController
和 WelcomeWorldController
。
1)控制器类
HelloWorldController.java
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC";
return new ModelAndView("hellopage", "message", message);
}
}
WelcomeWorldController.java
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WelcomeWorldController {
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "WELCOME SPRING MVC";
return new ModelAndView("welcomepage", "message", message);
}
}
2)视图组件
要运行此示例,它必须位于 WEB-INF/jsp
目录中。
hellopage.jsp
Message is: ${message}
welcomepage.jsp
Message is: ${message}
`3)Index 页面
它是可选的欢迎页面,提供调用两个控制器的链接。
<a href="hello.html">click</a>|
<a href="welcome.html">click</a>
Spring MVC请求响应示例
我们可以通过遵循Spring MVC来创建登录应用程序。我们需要在Controller类的请求处理方法中传递HttpServletRequest和HttpServletResponse对象。请看以下例子:
1)控制器类
HelloWorldController.java
package com.javatpoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld(HttpServletRequest request,HttpServletResponse res) {
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin")){
String message = "HELLO "+name;
return new ModelAndView("hellopage", "message", message);
}
else{
return new ModelAndView("errorpage", "message","Sorry, username or password error");
}
}
}
2) 视图组件
hellopage.jsp
Message is: ${message}
errorpage.jsp
${message}
<jsp:include page="/index.jsp"></jsp:include>
3) Index 页面
登录页面,用于接收用户的名称和密码。
<form action="hello.html" method="post">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
</form>
`Spring MVC表单示例
如何在不使用数据库的情况下处理spring MVC中的表单数据。在这里,我们将使用@Controler,@RequestMapping和@ModelAttribute注释。
要显示输入表单,我们将使用spring框架的 <form:form>
标记。先看一个简单的例子,将表单数据存储在模型对象中并显示列表的数据。
必需的Jar文件
您需要加载
Spring Core jar文件
Spring Web jar文件
download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.
index.jsp
<a href="empform">Add Employee</a>
<a href="viewemp">View Employees</a>
Emp.java
package com.javatpoint.beans;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public Emp() {
}
public Emp(int id, String name, float salary, String designation) {
super();
this.id = id;
this.name = name;
this.salary = salary;
this.designation = designation;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.javatpoint.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.javatpoint.beans.Emp;
@Controller
public class EmpController {
@RequestMapping("/empform")
public ModelAndView showform(){
//command is a reserved request attribute name, now use <form> tag to show object data
return new ModelAndView("empform","command",new Emp());
}
@RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("emp") Emp emp){
//write code to save emp object
//here, we are displaying emp object to prove emp has data
System.out.println(emp.getName()+" "+emp.getSalary()+" "+emp.getDesignation());
//return new ModelAndView("empform","command",emp);//will display object data
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
@RequestMapping("/viewemp")
public ModelAndView viewemp(){
//write the code to get all employees from DAO
//here, we are writing manual code of list for easy understanding
List<Emp> list=new ArrayList<Emp>();
list.add(new Emp(1,"rahul",35000f,"S.Engineer"));
list.add(new Emp(2,"aditya",25000f,"IT Manager"));
list.add(new Emp(3,"sachin",55000f,"Care Taker"));
return new ModelAndView("viewemp","list",list);
}
}
`web.xml
<?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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint.controllers"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
empform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
</tr>
</c:forEach>
</table>
Output :
Spring MVC CRUD示例
应用程序中CRUD(创建,读取,更新和删除)是创建任何项目中最重要的组成部分。它提供了开发大型项目的概念。在Spring MVC中,我们可以开发一个简单的CRUD应用程序。
在这里,我们使用 JdbcTemplate
进行数据库交互。
必需的Jar文件
Spring Core jar files
Spring Web jar files
ojdbc14.jar file for oracle
download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.
创建表格
这里,我们使用的是oracle 10g数据库的emp99表,它有4个字段:id,name,salary和designation。这里,id是自动递增的,它是由序列生成的。
Spring MVC CRUD示例
index.jsp
<a href="empform">Add Employee</a>
<a href="viewemp">View Employees</a>
` Emp.jsp
package com.javatpoint.beans;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
` EmpDao.java
package com.javatpoint.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.javatpoint.beans.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation)
values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+",
designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
EmpController.java
package com.javatpoint.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;
@Controller
public class EmpController {
@Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
@RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The @ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
@RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
@RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The @PathVariable puts URL data into variable.*/
@RequestMapping(value="/editemp/{id}")
public ModelAndView edit(@PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
@RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(@ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(@PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
web.xml
<?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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
`spring-servlet.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint.controllers"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.dao.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
empform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Employee</h1>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
empeditform.jsp
这里“/ SpringMVCCRUDSimple”是项目名称,如果您有不同的项目名称,请更改此名称。对于实时应用程序,您可以提供完整的URL。
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Employee</h1>
<form:form method="POST" action="/SpringMVCCRUDSimple/editsave">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Edit Save" /></td>
</tr>
</table>
</form:form>
viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td><a href="editemp/${emp.id}">Edit</a></td>
<td><a href="deleteemp/${emp.id}">Delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>
Output :
点击“Add New Employee”链接,你会看到以下表格。
填充数据并单击save按钮。你会看到employees 名单。
现在点击“edit”链接,数据将显示一个表单。
现在更改表单的数据并单击“edit save”按钮。
现在点击“delete”链接,你会看到删除记录的员工列表。
Spring MVC分页示例
分页用于在不同的部分显示大量的记录。在这种情况下,我们在一个页面中显示10条、20条或50条记录。对于剩余的记录,我们提供链接
我们可以简单地在Spring MVC中创建分页示例。以下这个分页示例中,我们使用mysql数据库来获取记录。
必需的Jar文件
运行此示例,您需要加载:
Spring Core jar文件
Spring Web jar文件
mysql-connector.jar文件
下载spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting,oxm,jdbc,orm等。
创建表或导入sql文件
这里,我们在“test”数据库中创建了“emp”表。emp表有三个字段:id,name和salary。手动创建表和插入记录或导入我们的sql文件。
Spring MVC分页示例
index.jsp
<a href="viewemp/1">View Employees</a>
Emp.java
package com.javatpoint.beans;
public class Emp {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
EmpDao.java
package com.javatpoint.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.javatpoint.beans.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Emp> getEmployeesByPage(int pageid,int total){
String sql="select * from Emp limit "+(pageid-1)+","+total;
return template.query(sql,new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
return e;
}
});
}
}
EmpController.java
package com.javatpoint.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;
@Controller
public class EmpController {
@Autowired
EmpDao dao;
@RequestMapping(value="/viewemp/{pageid}")
public ModelAndView edit(@PathVariable int pageid){
int total=5;
if(pageid==1){}
else{
pageid=(pageid-1)*total+1;
}
List<Emp> list=dao.getEmployeesByPage(pageid,total);
return new ModelAndView("viewemp","list",list);
}
}
web.xml
<?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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint.controllers"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value=""></property>
<property name="password" value=""></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.dao.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
viewemp.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
</tr>
</c:forEach>
</table>
<br/>
<a href="/SpringMVC/viewemp/1">1</a>
<a href="/SpringMVC/viewemp/2">2</a>
<a href="/SpringMVC/viewemp/3">3</a>
Output :
Spring MVC文件上传示例
Spring MVC提供了上传文件的简便方法,它可能是图像或其他文件。
必需的Jar文件
运行此示例,您需要加载:
Spring Core jar文件
Spring Web jar文件
commons-fileupload.jar和commons-io.jar文件
下载spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting,oxm,jdbc,orm等。
下载commons-io.jar
下载commons-fileupload.jar
Spring MVC文件上传步骤(相比MVC)
1)添加commons-io和fileupload.jar文件
2)在spring-servlet.xml中添加 CommonsMultipartResolver
的入口
< bean id = “multipartResolver”
class = “org.springframework.web.multipart.commons.CommonsMultipartResolver” />
3)创建表单以提交文件。方法名称必须为“ post
”,并且enctype为“ multiple/form-data
”。
<form action="savefile" method="post" enctype="multipart/form-data">
Select File: <input type="file" name="file"/>
<input type="submit" value="Upload File"/>
</form>
4)在<font color="#006600">Controller</font>中使用
CommonsMultipartFile`类。
@RequestMapping(value="/savefile",method=RequestMethod.POST)
public ModelAndView upload(@RequestParam CommonsMultipartFile file,HttpSession session){
String path=session.getServletContext().getRealPath("/");
String filename=file.getOriginalFilename();
System.out.println(path+" "+filename);
try{
byte barr[]=file.getBytes();
BufferedOutputStream bout=new BufferedOutputStream(
new FileOutputStream(path+"/"+filename));
bout.write(barr);
bout.flush();
bout.close();
}catch(Exception e){System.out.println(e);}
return new ModelAndView("upload-success","filename",path+"/"+filename);
}
5)在JSP中显示图像。
<h1>Upload Success</h1>
<img src="${filename}"/>
Spring MVC文件上传示例
创建图像目录
在项目中创建“images”目录,因为我们要通过编写代码来保存“/images”目录中的所有文件。
index.jsp
<a href="uploadform">Upload Image</a>
Emp.java
package com.javatpoint;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
private static final String UPLOAD_DIRECTORY ="/images";
@RequestMapping("uploadform")
public ModelAndView uploadForm(){
return new ModelAndView("uploadform");
}
@RequestMapping(value="savefile",method=RequestMethod.POST)
public ModelAndView saveimage( @RequestParam CommonsMultipartFile file,
HttpSession session) throws Exception{
ServletContext context = session.getServletContext();
String path = context.getRealPath(UPLOAD_DIRECTORY);
String filename = file.getOriginalFilename();
System.out.println(path+" "+filename);
byte[] bytes = file.getBytes();
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(
new File(path + File.separator + filename)));
stream.write(bytes);
stream.flush();
stream.close();
return new ModelAndView("uploadform","filesuccess","File successfully saved!");
}
}
web.xml
这里,需要为 CommonsMultipartResolver
创建一个bean。
<?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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
uploadform.jsp
这里的形式必须是 method=“post”
和 enctype=“multipart/form-data”
。
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<title>Image File Upload</title>
</head>
<body>
<h1>File Upload Example - JavaTpoint</h1>
<h3 style="color:red">${filesuccess}</h3>
<form:form method="post" action="savefile" enctype="multipart/form-data">
<p><label for="image">Choose Image</label></p>
<p><input name="file" id="fileToUpload" type="file" /></p>
<p><input type="submit" value="Upload"></p>
</form:form>
</body>
</html>
Output :
转到服务器控制台上打印的路径,以查看上载的文件。
END
以上是关于第七章 : Spring MVC教程示例的主要内容,如果未能解决你的问题,请参考以下文章
Spring MVC 3.2 Thymeleaf Ajax 片段
SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynami