学习目的是为了知道如何用Servlet实现 MVC,也是从原理上弄清楚SpringMVC。
一、工程目录
功能为用户输入 一个商品的信息,并提交,程序保存商品并展示已经保存的商品的信息。
所有的jsp文件都在WEB-INFO下,因此不能直接访问。
二、程序代码
- product
封闭了一个商品信息的javaBean .
package app02a.domain;
import java.io.Serializable;
public class Product implements Serializable{
private static final long serialVersionUID =1L;
private String name ;
private String description ;
private float price ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
- ProducForm
注意,下面的price 为String 类型。
package app02a.from;
/**
* ProductForm与html中的from相对应,是后者在服务端的代表。
* @author lsj
*/
public class ProductForm {
private String name ;
private String description ;
private String price ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
- 控制部分
package app02a.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import app02a.domain.Product;
import app02a.from.ProductForm;
public class ControllerServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
private void process(HttpServletRequest request, HttpServletResponse response){
String uri = request.getRequestURI() ;
int lastIndex =uri.lastIndexOf("/");
String action = uri.substring(lastIndex+1) ;
//execute an action
if (action.equals("produc_input.action")){
//nothing to do
}else if (action.equals("product_save.action")) {
//create form
ProductForm productForm = new ProductForm();
productForm.setName(request.getParameter("name"));
productForm.setDescription(request.getParameter("description"));
productForm.setPrice(request.getParameter("price"));
//create model
Product product = new Product() ;
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(Float.parseFloat(productForm.getPrice()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
//code to save product in DB
//store model in a scope variable for the view
//放入到了HttpServletRequest中,以便 对应的视图可以访问到
request.setAttribute("product", product);
}
//forward to a view
String dispatchUrl = null;
if (action.equals("product_input.action")){
dispatchUrl= "/WEB-INF/jsp/ProductForm.jsp" ;
}else if (action.equals("product_save.action")){
dispatchUrl= "/WEB-INF/jsp/ProductDetails.jsp" ;
}
//RequestDispatcher: Defines an object that receives requests from the client and
//sends them to any resource (such as a servlet, HTML file, or JSP file) on the server
if (dispatchUrl!= null){
RequestDispatcher rd = request.getRequestDispatcher(dispatchUrl) ;
try {
rd.forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 两个视图文件
ProductForm.jsp
<!DOCTYPE HTML>
<html>
<head>
<title>Add product from</title>
<style type ="text/css">@import url(css/main.css);</style>
</head>
<body>
<div id ="global">
<form action="product_save.action" method="post">
<fieldset>
<legend>add a product</legend>
<p>
<label for="name">Product Name</label>
<input type ="text" id ="name" name="name" tabindex="1">
</p>
<p>
<label for="description" >Description</label>
<input type ="text" id="description" name ="description" tabindex="2">
</p>
<p>
<label for="price">Price</label>
<input type="text" id ="price" name ="price" tabindex="3">
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="4">
<input id ="submit" type="submit" tabindex="5">
</p>
</fieldset>
</form>
</div>
</body>
</html>
ProductDetails.jsp
<!DOCTYPE HTML>
<html>
<head>
<title>Add product from</title>
<style type ="text/css">@import url(css/main.css);</style>
</head>
<body>
<div id="global">
<h4>The product has been saved</h4>
<p>
<h5>Details:</h5>
Product Name: ${product.name }<br/>
Description: ${product.description }<br/>
Price: ${product.price }<br/>
</p>
</div>
</body>
</html>
- servlet配置文件
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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_3_0.xsd"
version="3.0"
>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>app02a.servlet.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
- css文件
#global {
text-align: left;
border: 1px solid #dedede;
background: #efefef;
width: 560px;
padding: 20px;
margin: 100px auto;
}
form {
font:100% verdana;
min-width: 500px;
max-width: 600px;
width: 560px;
}
form fieldset {
border-color: #bdbebf;
border-width: 3px;
margin: 0;
}
legend {
font-size: 1.3em;
}
form label {
width: 250px;
display: block;
float: left;
text-align: right;
padding: 2px;
}
#buttons {
text-align: right;
}
最后,输入 http://localhost:8080/app02a/product_input.action
可以进行访问。
注意:在WEB-INF下的文件,如jsp,不可以通过浏览器直接访问,而应该通过action进行跳转。