工程结构:
步骤:
1. 先创建一个web工程
2. 把struts的开发包引入到web工程
3. 编写login.jsp
4. 编写ActionForm(用户表单)和Action(小队长→登录小队长)
5. 编写struts-config.xml文件,该文件用于配置Action和ActionForm,对应关系,跳转位置….,一般我们放在/WEB-INF目录下
6. 编写wel.jsp和err.jsp
7. 配置web.xml文件,该文件用于配置ActionServlet
8. 测试
代码如下:
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
</head>
<body>
<form action="/strutslogin/login.do" method="post">
u:<input type="text" name="username"/><br/>
p:<input type="password" name="password"/><br/>
<input type="submit" value="login"/><br/>
</form>
</body>
</html>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<jsp:forward page="/WEB-INF/login.jsp"/>
</body>
</html>
mysql.properties:
dbUserName=root
dbPassword=root
dbDriver=com.mysql.jdbc.Driver
dbUrl=jdbc\:mysql\://127.0.0.1\:3306/test?useUnicode\=true&characterEncoding\=utf8
SqlHelper.java:
package com.hsp.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.sql.*;
public class SqlHelper
{
//定义变量
private static Connection ct = null;
//大多数情况下用preparedstatement替代statement
private static PreparedStatement ps = null;
private static ResultSet rs = null;
//连接数据库的参数
private static String url = "";
private static String username = "";
private static String driver = "";
private static String passwd = "";
private static CallableStatement cs = null;
public static CallableStatement getCs()
{
return cs;
}
private static Properties pp = null;
private static InputStream fis = null;
//加载驱动,只需要一次,用静态代码块
static
{
try
{
//从dbinfo.properties
pp = new Properties();
fis=SqlHelper.class.getClassLoader().getResourceAsStream("mysql.properties");
//fis = new FileInputStream();
pp.load(fis);
url = pp.getProperty("dbUrl");
driver = pp.getProperty("dbDriver");
username = pp.getProperty("dbUserName");
passwd = pp.getProperty("dbPassword");
Class.forName(driver);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{ fis.close();}
catch(IOException e) {e.printStackTrace();}
fis = null;//垃圾回收站上收拾
}
}
//得到连接
public static Connection getConnection()
{
try
{ct = DriverManager.getConnection(url,username,passwd);}
catch(Exception e) {e.printStackTrace();}
return ct;
}
//*************callPro1存储过程函数1*************
public static CallableStatement callPro1(String sql,String[] parameters)
{
try{
ct = getConnection();
cs = ct.prepareCall(sql);
if(parameters!=null){
for(int i=0;i<parameters.length;i++){
cs.setObject(i+1,parameters[i]);
}
}
cs.execute();
}
catch(Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage());}
finally
{ close(rs,cs,ct);}
return cs;
}
//*******************callpro2存储过程2************************
public static CallableStatement callPro2(String sql,String[] inparameters,
Integer[] outparameters)
{
try
{
ct = getConnection();
cs = ct.prepareCall(sql);
if(inparameters!=null)
{
for(int i=0;i<inparameters.length;i++)
{
cs.setObject(i+1,inparameters[i]);
}
}
//cs.registerOutparameter(2,oracle.jdbc.OracleTypes.CURSOR);
if(outparameters!=null)
{
for(int i=0;i<outparameters.length;i++)
{
cs.registerOutParameter(inparameters.length+1+i,outparameters[i]);
}
}
cs.execute();
}
catch(Exception e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
}
finally
{
}
return cs;
}
public static ResultSet executeQuery(String sql,String[] parameters)
{
try
{
ct=getConnection();
ps=ct.prepareStatement(sql);
if(parameters!=null)
{
for(int i=0;i<parameters.length;i++)
{
ps.setString(i+1,parameters[i]);
}
}
rs = ps.executeQuery();
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
finally
{
}
return rs;
}
public static Connection getCt()
{
return ct;
}
public static PreparedStatement getPs()
{
return ps;
}
public static ResultSet getRs()
{
return rs;
}
public static void executeUpdate2(String[] sql,String[][] parameters)
{
try
{
ct = getConnection();
ct.setAutoCommit(false);
for(int i=0;i<sql.length;i++)
{
if(null!=parameters[i])
{
ps = ct.prepareStatement(sql[i]);
for(int j=0;j<parameters[i].length;j++)
{
ps.setString(j+1,parameters[i][j]);
}
ps.executeUpdate();
}
}
ct.commit();
}catch (Exception e)
{
e.printStackTrace();
try
{
ct.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
throw new RuntimeException(e.getMessage());
}finally
{
close(rs,ps,ct);
}
}
//先写一个update、delete、insert
//sql格式:update 表名 set 字段名 =?where 字段=?
//parameter神应该是(”abc“,23)
public static void executeUpdate(String sql,String[] parameters)
{
try
{
ct=getConnection();
ps = ct.prepareStatement(sql);
if(parameters!=null)
{
for(int i=0;i<parameters.length;i++)
{
ps.setString(i+1,parameters[i]);
}
}
ps.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();//开发阶段
//抛出异常
//可以处理,也可以不处理
throw new RuntimeException(e.getMessage());
}
finally
{
close(rs,ps,ct);
}
}
public static void close(ResultSet rs,Statement ps,Connection ct)
{
//关闭资源(先开后关)
if(rs!=null)
{
try
{
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
rs=null;
}
if(ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
ps=null;
}
if(null!=ct)
{
try
{
ct.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
ct=null;
}
}
}
Users.java:
package com.hsp.domain;
public class Users {
private int user_id;
private String user_pwd;
private String user_name;
private String user_email;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_pwd() {
return user_pwd;
}
public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
}
UsersService.java:
package com.hsp.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.hsp.domain.Users;
import com.hsp.utils.SqlHelper;
public class UsersService {
public boolean checkUser(Users user){
String sql="select * from users where user_name=? and user_pwd=?";
String parameters[]={user.getUser_name(),user.getUser_pwd()};
SqlHelper sqlHelper=new SqlHelper();
ResultSet rs=sqlHelper.executeQuery(sql, parameters);
try {
if(rs.next()){
return true;
}
else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
UserForm.java:
package com.hsp.forms;
//这是一个用户表单,用于填充数据
import org.apache.struts.action.ActionForm;
public class UserForm extends ActionForm {
//定义属性[这里有一个规范,就是我们定义属性名字的时候,应该和jsp页面的控件名称一致
//如果有人提出疑问:表单的属性名字是否必须和控件名一致?
//答:否,只要保证set和get方法和属性名存在关联:set属性名,如jsp控件名username,则set方法名必须为setUsername]
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;
}
}
LoginAction.java:
package com.hsp.actions;
//这是一个action(表示小队长,需要继承Action)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.hsp.domain.Users;
import com.hsp.forms.UserForm;
import com.hsp.service.UsersService;
public class LoginAction extends Action {
//我们需要重新编写一个方法:execute会被自动调用,有些类似servlet里的service方法和doGet和doPost方法
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//把form转成对应的UserForm对象
UserForm userForm=(UserForm)form;
//System.out.println("用户名="+userForm.getUsername());
//简单验证
// if("123".equals(userForm.getPassword())){
// //把名字存放到request对象域中
// //request.setAttribute("username", userForm.getUsername());
// //如果密码为123,就认为是合法用户
// return mapping.findForward("ok");//request.getRequestDispatcher.forward();
// }else{
// return mapping.findForward("err");
// }
//使用service(士兵到数据库去验证)
//创建一个Service
UsersService userService=new UsersService();
Users user=new Users();
user.setUser_name(userForm.getUsername());
user.setUser_pwd(userForm.getPassword());
if(userService.checkUser(user)){
return mapping.findForward("ok");
}else{
return mapping.findForward("err");
}
}
}
struts-config.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!-- 配置表单 -->
<form-beans>
<!-- name是表单名字,可以随意写,但是建议取名规范:表单类名首字母小写 -->
<!-- type用于指定表单类的全路径 -->
<form-bean name="userForm" type="com.hsp.forms.UserForm"/>
</form-beans>
<!-- 配置action -->
<action-mappings>
<!-- 配置具体的一个action,path:表示将来访问该action的资源名称,http://localhost:8080/web/path? -->
<!-- name:用于关联某个表单 -->
<!-- type:用于指定该action类的全路径 -->
<!-- scope="request"表示该action对应的表单对象的生命周期是request,相当于总控制器执行request.setAttribute("userForm",userForm); -->
<!-- scope="session"表示该action对应的表单对象的生命周期是session,相当于总控制器执行request.getSession.setAttribute("userForm",userForm); -->
<!-- scope=""默认是session -->
<action path="/login" name="userForm" scope="request" type="com.hsp.actions.LoginAction">
<!-- 配置跳转关系 -->
<!-- name表示结果名称,path:转发到哪个页面 -->
<forward name="ok" path="/WEB-INF/wel.jsp"/>
<forward name="err" path="/WEB-INF/err.jsp"/>
</action>
</action-mappings>
</struts-config>
wel.jsp:
<%@ page language="java" import="java.util.*,com.hsp.forms.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'wel.jsp' starting page</title>
</head>
<body>
wel <%=((UserForm)request.getAttribute("userForm")).getUsername() %><br/>
<a href="/strutslogin/">返回重新登录</a>
</body>
</html>
err.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'err.jsp' starting page</title>
</head>
<body>
err<br>
</body>
</html>
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">
<!-- 配置ActionServlet -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<!-- 配置struts-config,如果有多份配置文件,则用,分隔 -->
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 配置filter -->
<filter>
<filter-name>MyFilter1</filter-name>
<filter-class>com.hsp.filters.MyFilter1</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置首页文件 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
MyFilter1:
package com.hsp.filters;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter1 extends HttpServlet implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
arg0.setCharacterEncoding("utf-8");//设置接收编码
arg2.doFilter(arg0, arg1);//必须有这句话
arg1.setContentType("text/html;charset=utf-8");
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
以上是手工配置方式实现的struts案例,至于半手工方式和全自动方式在上一节“struts快速入门——笔记”中已经截图解说,提高了开发效率,代码部分则和手工方式一样。