使用一个简单的例子记录struts1开发过程。
index界面上只有两个超链接,分别可以打开录入产品界面和显示产品列表界面.
newProduct.jsp是录入的界面,searchProduct.jsp是查询列表的界面。
ProductAction.java是处理逻辑的action
添加完struts支持后,lib目录下会增添struts的jar包、增添struts的配置文件:/WEB-INF/struts-config.xml、同时在web.xml中增添了struts的配置。
第一步:在WebRoot/META-INF/下新建一个context文件,通过jndi方式配置数据源,context.xml文件内容如下:
3) 创建工具类EncodingFilter.java,自定义过滤器,并在web.xml中配置,参考web.xml配置中内容。EncodingFilter.java的内容如下:
7) Action处理类ProductAction.java如下:
0、 描述
主要功能描述:index界面上只有两个超链接,分别可以打开录入产品界面和显示产品列表界面.
newProduct.jsp是录入的界面,searchProduct.jsp是查询列表的界面。
ProductAction.java是处理逻辑的action
简单描述流程图:
1、 构建环境
在Myeclipse中,新建一个工程StrutsTest,选择该工程,右键Myeclipse->add sruts capapibality,弹出界面,选择struts1.2支持。如下图所示:添加完struts支持后,lib目录下会增添struts的jar包、增添struts的配置文件:/WEB-INF/struts-config.xml、同时在web.xml中增添了struts的配置。
3、 代码编写
1) 创建表结构,只有三个字段create table t_product
(
product_id varchar2(4) primary key,
product_name varchar2(50) not null,
price float
);
2) 创建工具类Util.java,从数据库连接池中获得连接。需要两个步骤
第一步:在WebRoot/META-INF/下新建一个context文件,通过jndi方式配置数据源,context.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
auth="Container"
name="jdbc/StrutsTestPool"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
username="apps"
password="apps"
maxActive="20"/>
</Context>
第二步:在util类中读取配置获得连接,util.java如下:
package com.company.struts.util;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Util {
/**
* 通过连接池得到连接
* @return
* @throws Exception
*/
public static Connection getPoolConnection() throws Exception{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/StrutsTestPool");
Connection conn = ds.getConnection();
return conn;
}
}
3) 创建工具类EncodingFilter.java,自定义过滤器,并在web.xml中配置,参考web.xml配置中内容。EncodingFilter.java的内容如下:
package com.company.struts.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
4) 修改web.xml,指定首页为index.jsp。文件内容如下:最后定义了一个fileld的过滤器,是用来过滤字符编码的,后面会提到。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 自定义的fileld 用来过滤字符编码 -->
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.company.struts.util.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5) 在WebRoot下打开index.jsp,去掉无用信息,写代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<title></title>
</head>
<body>
<br>
<br>
<br>
<table width = "500px" align = "center" height = "200px">
<tr><td>
<a href = "productAction.action?method=viewAddForm" target="black">input</a> <br /><br />
<a href = "productAction.action?method=query" target="black">search</a>
</td></tr>
</table>
</body>
</html>
6) index.jsp中提到productAction.action?method=viewAddForm,需要在struts的配置文件struts-config.xml中配置实现的action,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans>
<form-bean name="productForm" type="com.company.struts.vo.ProductVo" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/productAction" type="com.company.struts.action.ProductAction" parameter = "method" scope="request" name="productForm">
<forward name="viewNewProduct" path="/newProduct.jsp"></forward>
<forward name="viewSearchProduct" path="/searchProduct.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="com.company.struts.ApplicationResources" />
</struts-config>
在配置文件中配置了action的实现类,以及作为上传数据时用来保存数据的form: productForm
7) Action处理类ProductAction.java如下:
package com.company.struts.action;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.company.struts.util.Util;
import com.company.struts.vo.ProductVo;
public class ProductAction extends DispatchAction {
/**
* 转到新增界面
*/
public ActionForward viewAddForm(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward("viewNewProduct");
}
/**
* 转到查询界面
*/
public ActionForward viewSearchForm(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward("viewSearchProduct");
}
<span style="white-space:pre"> </span>/**
* 保存
*/
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String msg = "SUCCESS";
ProductVo vo = (ProductVo)form;
String validateResult = validate(vo);
if(validateResult != ""){
msg = validateResult;
}else{
Connection conn = null;
PreparedStatement psmt = null;
try {
conn = Util.getPoolConnection();
String sql = "insert into t_product(product_id,product_name,price) values" +
"('"+vo.getProductId()+"','"+vo.getProductName()+"','"+Float.parseFloat(vo.getPrice())+"')";
psmt = conn.prepareStatement(sql);
psmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
} finally{
if(psmt != null){
psmt.close();
}
if(conn != null){
conn.close();
}
}
}
request.setAttribute("error", msg);
return mapping.findForward("viewNewProduct");
}
<span style="white-space:pre"> </span>/**
*查询数据
*/
public ActionForward query(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String projectName = request.getParameter("queryTitle")== null?"":request.getParameter("queryTitle");
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
List<ProductVo> list = new ArrayList<ProductVo>();
try{
String sql = "select product_id,product_name,price from t_product where product_name like '%"+projectName+"%' order by product_id desc";
conn = Util.getPoolConnection();
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery(sql);
while(rs.next()){
ProductVo vo = new ProductVo();
vo.setProductId(rs.getString("product_id"));
vo.setProductName(rs.getString("product_name"));
vo.setPrice(rs.getString("price"));
list.add(vo);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(psmt != null){
psmt.close();
}
if(conn != null){
conn.close();
}
}
request.setAttribute("List", list);
return mapping.findForward("viewSearchProduct");
}
}
<span style="white-space:pre"> </span>/**
* 上传数据校验
*/
public String validate(ProductVo vo){
String returnStr = "";
if(vo == null){
returnStr = "不能传递空值";
}else{
if(vo.getProductId() == null || vo.getProductId() == ""
|| vo.getProductName() == null || vo.getProductName() == ""
|| vo.getPrice() == null || vo.getPrice() == ""){
returnStr = "值不能为空";
}
}
return returnStr;
}
8) 保存数据的form,ProductVo如下所示:
package com.company.struts.vo;
import org.apache.struts.action.ActionForm;
public class ProductVo extends ActionForm {
private static final long serialVersionUID = 1L;
private String productId;
private String productName;
private String price;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
9) newProduct.jsp是录入界面,代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head> <title></title> </head>
<body>
<!-- 读取request中的error信息,如果第一次进入,则为null,不弹出框,非首次则根据action判断的结果,弹出不同提示框 -->
<script type="text/javascript">
<%
Object msg = request.getAttribute("error");
if(msg != null){
String temp = msg.toString();
if(!temp.equals("SUCCESS")){
String err = "保存失败!原因:"+temp;
%>
alert("<%=err%>");
<%
}else{
%>
alert("保存成功!");
<%
}
}
%>
</script>
<form action="productAction.action?method=save" name = "newForm" id = "newForm" method = "post">
<table width = "500px" align = "center" height = "500px">
<tr>
<td>
ppprocuctID:
</td>
<td>
<input type = "text" name = "productId" id = "productId" />
</td>
</tr>
<tr>
<td>
pprocuctName:
</td>
<td>
<input type = "text" name = "productName" id = "productName" />
</td>
</tr>
<tr>
<td>
price:
</td>
<td>
<input type = "text" name = "price" id = "price" />
</td>
</tr>
<tr>
<td>
<input type = "submit" value = "summit" />
</td>
</tr>
</table>
</form>
</body>
</html>
10) searchProduct.jsp是查询结果界面,代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@page import="com.company.struts.vo.ProductVo"%>
<html>
<head>
<title></title>
</head>
<body>
<form action="productAction.action?method=query" name = "searchForm" id = "searchForm" method = "post">
<table width = "500px" align = "center">
<tr>
<td>
<input type = "text" name = "queryTitle" id = "queryTitle" />
<input type = "submit" name = "submit" id = "submit" value = "submit"/>
</td>
</tr>
</table>
<%
Object obj = request.getAttribute("List");
if(obj != null){
List<ProductVo> list = (List<ProductVo>)obj;
for(int i = 0;i<list.size();i++){
ProductVo vo = list.get(i);
%>
<table width = "500px" align = "center" border = "1px">
<tr>
<td>
ProductId
</td>
<td>
<%=vo.getProductId() %>
</td>
</tr>
<tr>
<td>
ProductName
</td>
<td>
<%=vo.getProductName() %>
</td>
</tr>
<tr>
<td>
Price
</td>
<td>
<%=vo.getPrice() %>
</td>
</tr>
</table>
<%
}
}
%>
</form>
</body>
</html>
至此,一个简单的例子就做完了,在浏览器输入
http://localhost:8080/StrutsTest
即可访问。