第一讲
struts基本概念
1.struts是一个框架frame
2.struts是一个web框架
3.struts是一个开源的框架
why struts?
mvc是一种模式
model view control
struts是基于mvc的web框架
mvc只告诉你怎么做,但还是有很大的区别
把数据的输入jsp、数据的处理控制器调用model,再输出到jsp
sun公司提供了基于mvc的web框架,
程序开发更加规范了,
程序开发的效率跟高了
程序的可读性提高了
程序的可维护性提高了
缺点是
form有点鸡肋
action是单态的(对网站的并发性有影响),
单态是指在整个程序的运行过程中始终是一个对象
框架提高了程序的规范,但也约束了程序员的自由。
struts-config.xml未必一定要放在WEB-INF,同时也要更改web.xml中的配置
在一个项目中可以有多个struts-config.xml配置文件
struts的运行原理
,以用户登录验证来讲解。
struts快速入门案例
,以用户登陆验证为例,使用手动配置的方式配置
开发步骤
需要struts开发包,建立一个web工程,引入包…写login.jsp
写ActonForm,必须继承actionForm,写Action,写struts-
config.xml
配置web.xml文件,写ok.jsp,写err.jsp
增加功能,在登陆成功后的页面显示用户名,
使用filter解决中文乱码问题
增加到数据库中验证用户是否合法的功能
在mysql中创建一个用户表
创建domain对象
手动开发struts 登录系统源码
web.xml
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<jsp:include page="/WEB-INF/login.jsp"></jsp:include>
</body>
</html>
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>
<form-bean name="userForm" type="com.xing.form.UserForm"/>
</form-beans>
<action-mappings>
<!-- scope="request" 相当于 request=request.setAttribute("userForm",userForm) -->
<!-- scope="session" 相当于 session=request.getSession().setAttribute("userForm",userForm) -->
<!-- scope 默认是session -->
<action path="/login" name="userForm" scope="request" type="com.xing.action.LoginAction">
<forward name="ok" path="/WEB-INF/ok.jsp"/>
<forward name="err" path="/WEB-INF/err.jsp"/>
</action>
</action-mappings>
</struts-config>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<jsp:include page="/WEB-INF/login.jsp"></jsp:include>
</body>
</html>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</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">
</form>
</body>
</html>
ok.jsp
<%@ page language="java" import="java.util.*,com.xing.form.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ok.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>WELCOME <%=((UserForm)request.getAttribute("userForm")).getUsername() %></h1><br>
<a href="/strutslogin/">返回重新登录</a>
</body>
</html>
err.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'err.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
</body>
</html>
Users.java
package com.xing.domain;
public class Users {
private int user_id;
private String user_pwd;
private String user_name;
private String user_email;
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_pwd() {
return user_pwd;
}
public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
}
}
UserForm.java
/*
* this is a actionForm used to fill data
*/
package com.xing.form;
import org.apache.struts.action.ActionForm;
public class UserForm extends ActionForm {
//定义属性,按照jsp控件名称定义,这是规范,应保证set和get方法和属性名称存在关联
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;
}
}
SqlHelper.java
/*
* 对数据库操作的类
* 对数据库的操作,就是crud
* 调用存储过程
*
*注意:如果连接数据库时出现如下异常则表示未引入三个JAR驱动包,另外一个原因就是SQL语句有语法错误
*java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDviver
* */
package com.xing.util;
import java.util.*;
import java.sql.*;
public class SqlHelper {
//定义需要的对象
Connection ct=null;
PreparedStatement ps=null;
ResultSet rs=null;
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url="jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=testdb";
String user="sa";
String passwd="tingwei";
//构造函数,初始化ct
public SqlHelper()
{
try {
//加载驱动
Class.forName(driver);
//得到连接
ct=DriverManager.getConnection(url,user,passwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//[]paras,通过?赋值方式可以防止漏洞注入方式,保证安全性
public ArrayList query(String sql,String []paras)
{
try {
ps=ct.prepareStatement(sql);
//对sql的参数赋值
for(int i=0;i<paras.length;i++)
{
ps.setString(i+1, paras[i]);
}
//执行查询
rs=ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
//返回结果集
ArrayList<ResultSet> al=new ArrayList<ResultSet>();
al.add(rs);
System.out.println(al.size()+" sdsfdsfs ");
return al;
}
//关闭资源的方法
public void close()
{
try {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(ct!=null) ct.close();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
UsersService.java
package com.xing.service;
import com.xing.domain.*;
import com.xing.util.*;
import java.util.ArrayList;
public class UsersService {
public boolean checkUser(Users user){
String sql="select * from users where username=? and passwd=?";
SqlHelper sqlHelper=new SqlHelper();
String []paras={user.getUser_name(),user.getUser_pwd()};
sqlHelper.query(sql, paras);
ArrayList al=sqlHelper.query(sql, paras);
if(al.size()==1){
return true;
}else return false;
}
}
LoginAction.java
package com.xing.action;
import com.xing.form.*;
import com.xing.service.*;
import com.xing.domain.*;
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;
public class LoginAction extends Action {
//重写方法,execute会被自动调用,类似Servlet/service
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//解决中文乱码问题
//request.setCharacterEncoding("utf-8");
//把form强转为对应的UserForm对象
UserForm userForm=(UserForm)form;
System.out.println("用户名="+userForm.getUsername()+" 密码="+userForm.getPassword());
//把名字存入request对象域
//request.setAttribute("username", userForm.getUsername());
/*简单验证
if("123".equals(userForm.getPassword())){
return mapping.findForward("ok");
}else{
return mapping.findForward("err");
}
*/
//使用service来验证,不要在action连接数据库
UsersService usersService=new UsersService();
Users user=new Users();
user.setUser_name(userForm.getUsername());
user.setUser_pwd(userForm.getPassword());
if(usersService.checkUser(user)){
return mapping.findForward("ok");
}else{
return mapping.findForward("err");
}
}
}
Myfilter1.java
package com.xing.filter;
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
}
}