struts2、hibernate和SSH的实现

Struts2

为什么开发Struts框架?

为了符合更加灵活、高效的开发需求

实质上Struts2是以WebWork为核心的,他采用拦截机制来处理用户请求。

(1)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>主页面</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="login" method="post"> 请输入学号:<input type="text" name="num"><br/><br/> <input type="submit" value="提交"/> </form> </body> </html>

(2)web.xml部分

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
> <!-- 指定struts2的核心过滤器 --> <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>

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter在lib里面,不同版本的struts对应的过滤器可能不一样,在这里的是2.4的版本

(3)lib部分

并不需要所有的包(导入所有的包可能会出现错误)

(4)servlet部分

package test;

public class ServletTest {
    private String mess;
    private String num;
    public String getMess() {
        return mess;
    }
    public void setMess(String mess) {
        this.mess = mess;
    }
    public String getNum() {
        return num;
    }
    public void setNum(String num) {
        this.num = num;
    }
    public String execute(){
        if(num.equals("111"))
            return "success";
        else
            return "wrong";
    }
}

(5)struts.xml部分

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default">
        <!-- 此处的name与index.jsp里面的action="login"对应 -->
        <!-- 此处的class是jsp对应的servlet类的完整名称 -->
        <action name="login" class="test.ServletTest">
            <!-- 此处的name与test.ServletTest.java里面的方法返回值相对应 -->
            <result name="success">/success.jsp</result>
            <result name="wrong">/wrong.jsp</result>
        </action>
    </package>
</struts>

 

 




 

 

Hibernate

为什么开发hibernate框架?

为了提高数据库访问层的编程速度,Gavin King 开发出了当今最流行的ORM框架——hibernate。

(1)实例类

package entity;

public class User {
    private int id;
    private String name;
    private int 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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}

(2)实体类对应的.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.test.array">
    <!-- 在class里面,name是实体类的类名,table表示对应的表名 -->
    <class name="entity.User" lazy="true" table="user">
        <!-- name="id"表示entity.User表里面的id属性,colum="id"表示user表的字段名为id -->
        <!-- 如果name和colum的值一样,不需要写colum -->
        <id name="id" column="id">
            <generator class="native"/><!-- 表示user表里面的id字段是自增型的 -->
        </id>
        <!-- 其他属性使用property标签来映射 -->
        <property name="name" column="name"/>
        <property name="age" column="age"/>
    </class>


</hibernate-mapping>

注意:每一个实体类与他对应的.hbm.xml文件同名

(3)lib

其实还有两个关于日志的包(教材上有介绍),但是在我下载的压缩文件里面没有找到

(4)Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <!-- 指定方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 数据库驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库url -->
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <!-- 数据库用户名,密码 -->
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!-- 显示SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 格式化SQL语句 -->
        <property name="format_sql">true</property>
        <!-- 用来关联hbm配置文件 -->
        <mapping resource="entity/User.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

(5)Dao

package dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import entity.User;

public class DAO {
    private Configuration cfg;
    private SessionFactory sf;
    private Session s;
    private Transaction ts;
    /**
     * 构造函数
     */
    public DAO(){
        //获取hibernate的配置信息
        cfg = new Configuration().configure();
        //更具config创建sessionFactory
        sf = cfg.buildSessionFactory();
        //更具factory创建session
        s = sf.openSession();//开启Session,相当于开启JDBC的Connection
        ts = s.beginTransaction();//创建事物的对象ts
    }
    /**
     * 添加信息到数据库
     * @param name
     * @param age
     * @return
     */
    public int AddUser(User u){
        int r=1;
        User user = new User();
        user.setName(u.getName());
        user.setAge(u.getAge());
        try{
            s.save(user);
            ts.commit();
        }catch(Exception e){
            e.printStackTrace();
            ts.rollback();
            System.out.println("添加失败!!");
            r=0;
        }finally{
            s.close();
            sf.close();
        }
        return r;
    }
    /**
     * 删除数据库信息
     * @param id
     * @return
     */
    public int DeletUser(int id){
        int r =1;
        User user = new User();
        user.setId(id);
        try{
            s.delete(user);
            ts.commit();
        }catch(Exception e){
            e.printStackTrace();
            ts.rollback();
            System.out.println("删除失败!!");
            r=0;
        }finally{
            s.close();
            sf.close();
        }
        return r;
    }
    /**
     * 更新数据库信息
     * @param u
     * @return
     */
    public int UpdateUser(User u){
        int r=1;
        User user = (User)s.get(User.class, u.getId());
        if(u.getAge()!=0){
            user.setAge(u.getAge());
        }
        if(u.getName().length()!=0){
            user.setName(u.getName());
        }
        try{
            s.update(user);
            ts.commit();
        }catch(Exception e){
            e.printStackTrace();
            ts.rollback();
            System.out.println("更新失败!!");
            r=0;
        }finally{
            s.close();
            sf.close();
        }
        return r;
    }
    /**
     * 查询数据库所有信息
     * @return
     */
    public List QueryUser(){
        User user = new User();
        Query query = s.createQuery("from User");//注意!!这里是:from 实例类名
        List users = query.list();//序列化
        //迭代
        Iterator it = users.iterator();
        while(it.hasNext()){
            user=(User)it.next();
            System.out.println(user.getId()+"号"+user.getName()+" "+user.getAge()+"岁");
        }
        return users;
    }
    /**
     * 查询数据库所有名字是name的信息
     * @param name
     * @return
     */
    public List FindUserByName(String name){
        User user = new User();
        Query query = s.createQuery("from User where name='"+name+"'");//注意!!这里是:from 实例类名
        List users = query.list();//序列化
        //迭代
        Iterator it = users.iterator();
        while(it.hasNext()){
            user=(User)it.next();
            System.out.println(user.getId()+"号"+user.getName()+" "+user.getAge()+"岁");
        }
        return users;
    }
    /**
     * 查询数据库所有id是id的信息
     * @param id
     * @return
     */
    public User FindUserById(int id){
        User user = (User)s.get(User.class, id);
        return user;
    }
}

(6)数据库的增删查改

A:添加信息到数据库

package action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import dao.DAO;

public class Add  extends HttpServlet{
    public void service(HttpServletRequest request,HttpServletResponse response){
        String mess="添加用户信息成功!!";
        String user = "minuobaci";
        int age = 12;
        User u = new User();
        u.setAge(age);
        u.setName(user);
        DAO dao = new DAO();
        int r = dao.AddUser(u);
        if(r==0){
            mess="添加用户信息失败!!";
            System.out.println("添加用户信息失败!!");        
        }
        try {
            request.setAttribute("mess", mess);
            request.getRequestDispatcher("/all").forward(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

B:删除数据库信息

package action;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.DAO;

public class Delete extends HttpServlet{
    public void service(HttpServletRequest request,HttpServletResponse response){
        String mess="删除用户信息成功!!";
        int id = 1;
        
        DAO dao = new DAO();
        int r = dao.DeletUser(id);
        if(r==0){
            mess="删除用户信息失败!!";
            System.out.println("删除用户信息失败!!");        
        }
        try {
            request.setAttribute("mess", mess);
            request.getRequestDispatcher("/all").forward(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

C:遍历数据库所有信息

package action;



import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.User;
import dao.DAO;

public class Find extends HttpServlet{
    public void service(HttpServletRequest request,HttpServletResponse response){
        String user = "minuobaci";
        DAO dao = new DAO();
        List lists =  dao.FindUserByName(user);
        for(User u:lists){
            System.out.println("username: "+u.getId()+" age:"+u.getName())
        }
    }
}

 

 




 

 

 

SSH

1:创建web项目并导入对应的jar包

2:修改web.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
> <!-- spring 监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- 指定struts2的核心过滤器 --> <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>

3:创建实体类

package com.gx.entity;

public class User {
    private int id;
     private String name;
     private int 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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

4:创建实体类对应的hibernate配置文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.test.array">
    <!-- 在class里面,name是实体类的类名,table表示对应的表名 -->
    <class name="com.gx.entity.User" lazy="true" table="user">
        <!-- name="id"表示entity.User表里面的id属性,colum="id"表示user表的字段名为id -->
        <!-- 如果name和colum的值一样,不需要写colum -->
        <id name="id" column="id">
            <generator class="native"/><!-- 表示user表里面的id字段是自增型的 -->
        </id>
        <!-- 其他属性使用property标签来映射 -->
        <property name="name" column="name"/>
        <property name="age" column="age"/>
    </class>


</hibernate-mapping>

5:创建spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                   http://www.springframework.org/schema/beans/spring-beans.xsd
                   http://www.springframework.org/schema/context
                   http://www.springframework.org/schema/context/spring-context.xsd
                   http://www.springframework.org/schema/tx
                   http://www.springframework.org/schema/tx/spring-tx.xsd
                   http://www.springframework.org/schema/aop
                   http://www.springframework.org/schema/aop/spring-aop.xsd">
 
    <bean name="sf"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="ds" />
        <property name="mappingResources">
            <list>
                <value>com/gx/entity/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
                hbm2ddl.auto=update
            </value>
        </property>
    </bean>    
         
    <bean name="ds"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3307/test?characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>   
</beans>

6:创建Dao接口

package com.gx.dao;

import java.util.List;

import com.gx.entity.User;

public interface UserDAO {
    //增加用户
    public int addUser(User user);
    //删除用户
    public int deleteUser(User user);
    //通过id查询用户
    public User findUserById(int id);
    //通过用户名查询用户
    public List<User> findUserByName(String name);
    //查询所有用户
    public List<User> findAll();
    //修改用户
    public int updateUser(User user);
}

7:创建Dao接口的实现类

package com.gx.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gx.entity.User;

public class UserDAOImp extends HibernateDaoSupport implements UserDAO{
    /**
     * 增加用户
     */
    public int addUser(User user){
        int r=1;
        System.out.println("########################################");
        try{
            this.getHibernateTemplate().save(user);
            System.out.println("在UserDAOImp里面的addUser方法中添加用户成功!!");
            System.out.println("########################################");
        }catch(Exception  e){
            r=0;
            System.out.println("在UserDAOImp里面的addUser方法中添加用户失败……");
            System.out.println("########################################");
        }
        return r;
    }
    /**
     *删除用户
     */
    public int deleteUser(User user){
        int r=1;
        System.out.println("########################################");
        try{
            this.getHibernateTemplate().delete(user);
            System.out.println("在UserDAOImp里面的deleteUser方法中删除用户成功!!");
            System.out.println("########################################");
        }catch(Exception  e){
            r=0;
            System.out.println("在UserDAOImp里面的deleteUser方法中删除用户失败……");
            System.out.println("########################################");
        }
        return r;
    }
    /**
     * 通过用户名查询用户
     */
    public List<User> findUserByName(String name){
        ApplicationContext context = 
          new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" }); SessionFactory lsf = (SessionFactory) context.getBean("sf"); Session session = lsf.openSession(); Transaction t = session.beginTransaction(); String hql="from User where name='"+name+"'"; System.out.println("########################################"); System.out.println("在UserDAOImp里面的findUserByName方法中hql="+hql); System.out.println("########################################"); List<User> users = session.createQuery(hql).list(); return users; } /** * 查询所有用户 */ public List<User> findAll(){ return this.getHibernateTemplate().find("from User"); } /** * 通过id查询用户 */ public User findUserById(int id){ return (User)this.getHibernateTemplate().get(User.class, id); } /** * 修改用户 */ public int updateUser(User user){ int r=1; System.out.println("########################################"); try{ this.getHibernateTemplate().update(user); System.out.println("在UserDAOImp里面的updateUser方法中更新用户成功!!"); System.out.println("########################################"); }catch(Exception e){ r=0; System.out.println("在UserDAOImp里面的updateUser方法中更新用户失败……"); System.out.println("########################################"); } return r; } }

8:在applicationContext.xml添加以下代码

    <bean name="UserDAO" class="com.gx.dao.UserDAOImp">
        <property name="sessionFactory" ref="sf" />
    </bean>

9:创建Service接口

package com.gx.service;

import java.util.List;

import com.gx.entity.User;

public interface UserService {
    //添加用户
    public String addUser(User user);
    //通过id查询用户
    public User findUserByID(int id);
    //查询所有用户
    public List<User> findAll ();
    //通过用户名查询
    public List<User> findUserByName(String name); 
    //删除用户
    public String deleteUser(User user);
    //更新用户
    public String updateUser(User user);
}

10:创建Service接口的实现类

package com.gx.service;

import java.util.List;

import com.gx.dao.UserDAO;
import com.gx.entity.User;

public class UserServiceImp implements UserService{
    private UserDAO udao;
    public UserDAO getUdao() {
        return udao;
    }
    public void setUdao(UserDAO udao) {
        this.udao = udao;
    }
    /**
     * 更新用户
     */
    public String updateUser(User user){
        System.out.println("***********************************************");
        System.out.println("正在执行UserServiceImp中的updateUser方法……");
        System.out.println("***********************************************");
        int r = udao.updateUser(user);
        if(r==0)
            return "更新失败!!";
        else
            return "ok";
    }
    /**
     * 添加用户
     */
    public String addUser(User user){
        System.out.println("***********************************************");
        System.out.println("正在执行UserServiceImp中的addUser方法……");
        System.out.println("***********************************************");
        int r = udao.addUser(user);
        if(r==0)
            return "添加用户失败!!";
        return "ok";
    }
    /**
     * 查询所有用户
     */
    public List<User> findAll (){
        return udao.findAll();
    }
    /**
     * 通过用户名查询
     */
    public List<User> findUserByName(String name){
        System.out.println("***********************************************");
        System.out.println("正在执行UserServiceImp中的findUserByName方法……");
        System.out.println("***********************************************");
        return udao.findUserByName(name);
    }
    /**
     * 删除用户
     */
    public String deleteUser(User user){
        System.out.println("***********************************************");
        System.out.println("正在执行UserServiceImp中的deleteUser方法……");
        System.out.println("***********************************************");
        int r = udao.deleteUser(user);
        if(r==0)
            return "删除用户失败!!";
        else
            return "ok";
    }
    /**
     * 通过id查询用户
     */
    public User findUserByID(int id){
        return udao.findUserById(id);
    }
}

11:在applicationContext.xml里面添加以下代码

    <bean id="UserService" class="com.gx.service.UserServiceImp">
           <property name="udao" ref="UserDAO"></property>
    </bean>

12:创建Action接口

package com.gx.action;

public interface UserAction {
    //添加用户
    public String add();
    //显示所有的用户
    public String show();
    //显示所查询的用户
    public String find();
    //删除用户
    public String delete();
    //更新用户,获得用户信息
    public String updateGet();
    //更新用户 更新信息
    public String update();
}

13:创建Action的实现类

package com.gx.action;

import java.util.List;
import com.gx.service.UserService;
import com.gx.entity.User;
public class UserActionImp implements UserAction{
    private UserService uservice;
    private List<User> users;
    private User user;
    private String mess;
    public String getMess() {
        return mess;
    }
    public void setMess(String mess) {
        this.mess = mess;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public UserService getUservice() {
        return uservice;
    }
    public void setUservice(UserService uservice) {
        this.uservice = uservice;
    }
    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }
    /**
     * 添加用户
     */
    public String add(){
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        System.out.println("在UserActionImp中的add方法中");
        System.out.println(user.toString());
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        mess = uservice.addUser(user);
        if(mess.equals("ok")){
            users = uservice.findAll();
            return "addtrue";
        }else{
            return "addfalse";
        }
    }
    /**
     * 显示所有的用户
     */
    public String show(){
        users = uservice.findAll();
        return "addtrue";
    }
    /**
     * 显示所查询的用户
     */
    public String find(){
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        System.out.println("正在执行UserActionImp中的find方法……");
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        users = uservice.findUserByName(user.getName());
        return "addtrue";
    }
    /**
     * 删除用户
     */
    public String delete(){
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        System.out.println("正在执行UserActionImp中的delete方法……");
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        User u = uservice.findUserByID(user.getId());
        mess = uservice.deleteUser(u);
        if(mess.equals("ok"))
            mess="删除用户成功!!";
        users = uservice.findAll();
        return "addtrue";
    }
    /**
     * 更新用户 , 获得用户信息
     */
    public String updateGet(){
        user = uservice.findUserByID(user.getId());
        return "updatetrue";
    }
    /**
     * 更新用户信息 , 更新用户信息
     */
    public String update(){
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        System.out.println("正在执行UserActionImp中的update方法……");
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        User u = uservice.findUserByID(user.getId());
        u.setAge(user.getAge());
        u.setName(user.getName());
        mess = uservice.updateUser(u);
        if(mess.equals("ok")){
            users = uservice.findAll();
            return "addtrue";
        }
        return "updatetrue";
    }
}

14:在applicationContext.xml文件里面添加以下代码

<bean id="User" class="com.gx.action.UserActionImp">
   <property name="uservice" ref="UserService"></property>
</bean>

15:创建Struts2配置文件struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default">
        <action name="user_*" class="User" method="{1}">
            <result name="addtrue">/index.jsp</result>
            <result name="addfalse">/addUser.jsp</result>
            <result name="updatetrue">/updateUser.jsp</result>
        </action>
    </package>
</struts>

16:创建index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = 
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>主页面</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="css/index.css"> </head> <body> <form action="user_find" method="post"> <input id="find" type="text" name="user.name" placeholder="请输入需要查找的用户名" /> <input id="fs" type="submit" value="查询" /> </form> <hr> <div id="mess">${mess}</div> <table id="table"> <tr> <td>用户id</td> <td>用户名</td> <td>用户年龄</td> <td>更新用户</td> <td>删除用户</td> </tr> <c:forEach items="${users}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> <td><a style="color:yellow" href="user_updateGet?user.id=${user.id}">更新</a></td> <td><a style="color:red" href="user_delete?user.id=${user.id}">删除</a></td> </tr> </c:forEach> </table> </body> </html>

17:创建addUser.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>添加用户</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"> </head> <body> <div id="mess">${mess}</div> <div id="back"> <div id="title">添加用户|ADD</div> <form action="user_add" method="post"> <div id="bottom"> <br/> <input class="input" name="user.name" type="text" placeholder="请输入用户名" /><br/> <input class="input" name="user.age" type="text" placeholder="请输入用户年龄" /><br/> <br/><a id="a" href="user_show">返回主页面</a><br/> <input id="up" type="submit" value="添加" /><br/><br/> </div> </form> </div> </body> </html>

18:创建updateUser.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>更新用户</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"> </head> <body> <div id="mess">${mess}</div> <div id="back"> <div id="title">更新用户|UPDATE</div> <form action="user_update" method="post"> <div id="bottom"> <br/> 请输入用户名 <input class="input" name="user.name" value="${user.name}" type="text"/><br/> 请输入用户年龄 <input class="input" name="user.age" value="${user.age}" type="text"/><br/> <br/><a id="a" href="user_show">返回主页面</a><br/> <input id="up" type="submit" value="添加" /><br/><br/> </div> </form> </div> </body> </html>

 

posted @ 2017-09-17 17:15  米诺八慈  阅读(225)  评论(0编辑  收藏  举报