首先要知道mvc模式(model,view,controller),controller层用来接收页面请求的信息,并且调用service层来响应给界面信息。model层用来处理业务信息和数据库的交互,view用来显示界面信息。Struts就是mvc模式的优秀代表,struts最主要的是处理mvc的controller层。他用一个过滤器来代替controller层,具体的操作交给action。
首先在web.xml配置struts的过滤器,让所有的请求都经过这个过滤器,StrutsPrepareAndExecuteFilter类会根据struts配置文件找到相应的action进行处理
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
做一个产品添加
创建Product.java
public class Product {
int id;
String name;
int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
}
}
创建addProduct.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="addProduct" method="post">
<input type="text" name="product.age">
<input type="text" name="product.name">
<br/>
<input type="submit" value="submit">
</form>
</body>
</html>
编写action类,处理t添加请求,struts会根据传来的参数自动给属性赋值。但必须要表单中的name和属性的名称一致且生成get set 方法
public class ProductAction {
private Product product;
public String add(){
System.out.println("product.name:"+product.getName());
System.out.println("product.name:"+product.getAge());
return "show";
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
在struts.xml中
<action name="addProduct" class="com.how2java.action.ProductAction" method="add">
<result name="show">show.jsp</result>
</action>