【示例】Spring和Struts整合

此例子来自于《JavaEE企业应用实战》(李刚)

需要先导入spring和struts的jar包,一定要导入struts2-spring-plugin-版本号.jar,这是让spring和struts相关联的包。接下来是例子

struts.xml(在src文件下)




    
    
    
        
        
            error.jsp
            success.jsp
        
        
            {1}.jsp
        
    

web.xml(WEB-INF文件夹下)



  TestStruts5
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
    
    
        org.springframework.web.context.ContextLoaderListener
        
    
    
        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
    
        struts2
        /*
    
 

applicationContext.xml(在WEB-INF文件夹下)



    
    

注意:对Action配置一定要加scope属性,因为Action包含了请求的状态信息,必须为每个请求对应一个Action,所以不能将该Action实例配置成singleton行为

MyService接口

package com.service;

public interface MyService {
    int validLogin(String username , String pass);
}

MyService接口实现类

package com.service.impl;

import com.service.MyService;

public class MyServiceImpl implements MyService {

    @Override
    public int validLogin(String username, String pass) {
        // TODO Auto-generated method stub
        if(username.equals(pass)) {
            return 99;
        }
        return -1;
    }

}

Action类

package com.action;

import com.opensymphony.xwork2.ActionSupport;
import com.service.MyService;

public class LoginAction extends ActionSupport {
    private String username;
    private String password;
    private MyService myService;
    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;
    }
    public void setMyService(MyService myService) {
        this.myService = myService;
    }
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        if(myService.validLogin(username, password) > 0) {
            return SUCCESS;
        }
        return ERROR;
    }
}

这里的myService只需要加set方法以便依赖注入。


接下来是测试用的页面
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>




Insert title here



    
    
    



还需要一个success.jsp和error.jsp页面来代表action相应是成功还是失败的,我这里I就不写出来了。

你可能感兴趣的:(【示例】Spring和Struts整合)