SpringMVC +Spring+ SpringJDBC 整合 教程

项目文件结构,如下截图:

SpringMVC +Spring+ SpringJDBC 整合 教程_第1张图片

第一步:整合web.xml 文件,主要实现SpringMVC监听器(DispatchServlet)、编码过滤器、Spring监听器和内存监听器



	
	
	
		contextConfigLocation
		classpath:spring-mybatis.xml
	
	
	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	
	
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		org.springframework.web.util.IntrospectorCleanupListener
	

	
	
		SpringMVC
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:spring-mvc.xml
		
		1
	
	
		SpringMVC
		
		/
	
	
		/index.jsp
	


第二步:spring-mvc.xml 和spring-mybatis.xml 配置


	
	
  	 
	
	
	
	 
	 
		
	
	
	

	
	
	 
	
	
	
	
	
	
		
			
				text/html;charset=UTF-8
			
		
	
	
	
		
			
					
			
		
	
	
	
		
		
		
        
        
        
	
	
	
	  
        
          
        
          
        
          
     












   
 	
			
		
			  
                classpath:jdbc.properties  
                classpath:memcache.properties  
             
		
	

	
		
		
		
		

		
		
		
		

		
		

		
		

		
		

		
		
		
		

		
		
		

		
		
	


	
	
	
	
        
    
	
    
        
    
	
	
		
	

	
	 
        
            
        
    

	
		
		
		
	

	
	 

        
            memCachedPool
        
        
        
            
                ${memcache.server}
            
        
        
        
            ${memcache.initConn}
        
        
        
            ${memcache.minConn}
        

        
            ${memcache.maxConn}
        

        
            ${memcache.maintSleep}
        

        
            ${memcache.nagle}
        

        
            ${memcache.socketTO}
        
    

    
    	
    		memCachedPool
    	
    
    
    
    
    	
    		       
    	    
    

3、实体类(OauthClient和OauthUser)

package com.wlsq.oauth.pojo;

public class OauthClient implements java.io.Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Long id;
	private String clientName;
	private String clientId;
	private String clientScerct;
	
	
	public OauthClient() {		
	}
	
	public OauthClient(Long id, String clientName, String clientId,
			String clientScerct) {
		super();
		this.id = id;
		this.clientName = clientName;
		this.clientId = clientId;
		this.clientScerct = clientScerct;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getClientName() {
		return clientName;
	}
	public void setClientName(String clientName) {
		this.clientName = clientName;
	}
	public String getClientId() {
		return clientId;
	}
	public void setClientId(String clientId) {
		this.clientId = clientId;
	}
	public String getClientScerct() {
		return clientScerct;
	}
	public void setClientScerct(String clientScerct) {
		this.clientScerct = clientScerct;
	}
	
	

}

package com.wlsq.oauth.pojo;

public class OauthUser implements java.io.Serializable  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Long id;
	private String username;
	private String password;
	private String salt;
	
	public OauthUser() {		
	}
	
	public OauthUser(Long id, String username, String password, String salt) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.salt = salt;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	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 String getSalt() {
		return salt;
	}
	public void setSalt(String salt) {
		this.salt = salt;
	}
	
	

	
}

4、dao层和dao层 实现

package com.wlsq.oauth.dao;

import java.util.List;

import com.wlsq.oauth.pojo.OauthClient;

public interface OauthClientMapper {
	public OauthClient createClient(OauthClient client);// 创建客户端

	public OauthClient updateClient(OauthClient client);// 更新客户端

	public void deleteClient(Long clientId);// 删除客户端

	OauthClient findOne(Long clientId);// 根据id查找客户端

	List findAll();// 查找所有

	OauthClient findByClientId(String clientId);// 根据客户端id查找客户端

	OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
}
package com.wlsq.oauth.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import com.wlsq.oauth.pojo.OauthClient;

@Repository
public class OauthClientMapperImpl implements OauthClientMapper {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public OauthClient createClient(final OauthClient client) {
		// TODO Auto-generated method stub
		final String sql = "insert into oauth2_client(client_name, client_id, client_secret) values(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                int count = 1;
                psst.setString(count++, client.getClientName());
                psst.setString(count++, client.getClientId());
                psst.setString(count++, client.getClientScerct());
                return psst;
            }
        }, keyHolder);

        client.setId(keyHolder.getKey().longValue());
        return client;
	}

	@Override
	public OauthClient updateClient(OauthClient client) {
		// TODO Auto-generated method stub
		  String sql = "update oauth2_client set client_name=?, client_id=?, client_secret=? where id=?";
	        jdbcTemplate.update(
	                sql,
	                client.getClientName(), client.getClientId(), client.getClientScerct(), client.getId());
	        return client;
	}

	@Override
	public void deleteClient(Long clientId) {
		// TODO Auto-generated method stub
		 String sql = "delete from oauth2_client where id=?";
	     jdbcTemplate.update(sql, clientId);
	}

	@Override
	public OauthClient findOne(Long clientId) {
		// TODO Auto-generated method stub
		  String sql = "select id, client_name, client_id, client_secret from oauth2_client where id=?";
	        List clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
	        if(clientList.size() == 0) {
	            return null;
	        }
	        return clientList.get(0);
	}

	@Override
	public List findAll() {
		// TODO Auto-generated method stub
		   String sql = "select id, client_name, client_id, client_secret from oauth2_client";
	        return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class));
	}

	@Override
	public OauthClient findByClientId(String clientId) {
		// TODO Auto-generated method stub
		  String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_id=?";
	        List clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
	        if(clientList.size() == 0) {
	            return null;
	        }
	        return clientList.get(0);
	}

	@Override
	public OauthClient findByClientSecret(String clientSecret) {
		// TODO Auto-generated method stub
		 String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_secret=?";
	        List clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientSecret);
	        if(clientList.size() == 0) {
	            return null;
	        }
	        return clientList.get(0);
	}

}


package com.wlsq.oauth.dao;

import java.util.List;

import com.wlsq.oauth.pojo.OauthUser;

public interface OauthUserMapper {
	 public OauthUser createUser(OauthUser user);// 创建用户  
	    public OauthUser updateUser(OauthUser user);// 更新用户  
	    public void deleteUser(Long userId);// 删除用户  
	    public void changePassword(Long userId, String newPassword); //修改密码  
	    OauthUser findOne(Long userId);// 根据id查找用户  
	    List findAll();// 得到所有用户  
	    public OauthUser findByUsername(String username);// 根据用户名查找用户  
}
package com.wlsq.oauth.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import com.wlsq.oauth.pojo.OauthUser;
@Repository
public class OauthUserMapperImpl implements OauthUserMapper {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public OauthUser createUser(final OauthUser user) {
		final String sql = "insert into oauth2_user(username, password, salt) values(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                int count = 1;
                psst.setString(count++, user.getUsername());
                psst.setString(count++, user.getPassword());
                psst.setString(count++, user.getSalt());
                return psst;
            }
        }, keyHolder);

        user.setId(keyHolder.getKey().longValue());
        return user;    
	}

	@Override
	public OauthUser updateUser(OauthUser user) {
		// TODO Auto-generated method stub
		   String sql = "update oauth2_user set username=?, password=?, salt=? where id=?";
	       jdbcTemplate.update(
	                sql,
	                user.getUsername(), user.getPassword(), user.getSalt(), user.getId());
	        return user;
	}

	@Override
	public void deleteUser(Long userId) {
		// TODO Auto-generated method stub
		  String sql = "delete from oauth2_user where id=?";
	      jdbcTemplate.update(sql, userId);
	}

	@Override
	public void changePassword(Long userId, String newPassword) {
		// TODO Auto-generated method stub

	}

	@Override
	public OauthUser findOne(Long userId) {
		// TODO Auto-generated method stub
		String sql = "select id, username, password, salt from oauth2_user where id=?";
        List userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), userId);
        if(userList.size() == 0) {
            return null;
        }
        return userList.get(0);
	}

	@Override
	public List findAll() {
		// TODO Auto-generated method stub
		 String sql = "select id, username, password, salt from oauth2_user";
	     return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class));
	}

	@Override
	public OauthUser findByUsername(String username) {
		// TODO Auto-generated method stub
		 String sql = "select id, username, password, salt from oauth2_user where username=?";
	        List userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), username);
	        if(userList.size() == 0) {
	            return null;
	        }
	        return userList.get(0);
	}

}
3、service层和service层实现

package com.wlsq.oauth.service;

import java.util.List;



import com.wlsq.oauth.pojo.OauthClient;


public interface IOauthClientMapperService {
	public OauthClient createClient(OauthClient client);// 创建客户端

	public OauthClient updateClient(OauthClient client);// 更新客户端

	public void deleteClient(Long clientId);// 删除客户端

	OauthClient findOne(Long clientId);// 根据id查找客户端

	List findAll();// 查找所有

	OauthClient findByClientId(String clientId);// 根据客户端id查找客户端

	OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
}
package com.wlsq.oauth.service.impl;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wlsq.oauth.dao.OauthClientMapper;
import com.wlsq.oauth.pojo.OauthClient;
import com.wlsq.oauth.service.IOauthClientMapperService;

@Transactional
@Service("oauthClientService")
public class OauthClientServiceImpl implements IOauthClientMapperService {
	@Autowired
	private OauthClientMapper clientDao;
	@Override
	public OauthClient createClient(OauthClient client) {
		// TODO Auto-generated method stub
		client.setClientId(UUID.randomUUID().toString());
        client.setClientScerct(UUID.randomUUID().toString());
        return clientDao.createClient(client);
	}

	@Override
	public OauthClient updateClient(OauthClient client) {
		// TODO Auto-generated method stub
		return clientDao.updateClient(client);
	}

	@Override
	public void deleteClient(Long clientId) {
		// TODO Auto-generated method stub
		clientDao.deleteClient(clientId);
	}

	@Override
	public OauthClient findOne(Long clientId) {
		// TODO Auto-generated method stub
		return clientDao.findOne(clientId);
	}

	@Override
	public List findAll() {
		// TODO Auto-generated method stub
		return clientDao.findAll();
	}

	@Override
	public OauthClient findByClientId(String clientId) {
		// TODO Auto-generated method stub
		return clientDao.findByClientId(clientId);
	}

	@Override
	public OauthClient findByClientSecret(String clientSecret) {
		// TODO Auto-generated method stub
		return clientDao.findByClientSecret(clientSecret);
	}

}


package com.wlsq.oauth.service;

import java.util.List;

import com.wlsq.oauth.pojo.OauthUser;

public interface IOauthUserMapperService {
	public OauthUser createUser(OauthUser user);// 创建用户  
    public OauthUser updateUser(OauthUser user);// 更新用户  
    public void deleteUser(Long userId);// 删除用户  
    public void changePassword(Long userId, String newPassword); //修改密码  
    OauthUser findOne(Long userId);// 根据id查找用户  
    List findAll();// 得到所有用户  
    public OauthUser findByUsername(String username);// 根据用户名查找用户  
}
package com.wlsq.oauth.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.wlsq.oauth.dao.OauthUserMapper;
import com.wlsq.oauth.pojo.OauthUser;
import com.wlsq.oauth.service.IOauthUserMapperService;

@Transactional
@Service("oauthUserService")
public class OauthUserServiceImpl implements IOauthUserMapperService {
	@Autowired
	private OauthUserMapper  oauthUserMapper;
	@Override
	public OauthUser createUser(OauthUser user) {
		// TODO Auto-generated method stub
		return this.oauthUserMapper.createUser(user);
	}

	@Override
	public OauthUser updateUser(OauthUser user) {
		// TODO Auto-generated method stub
		return this.oauthUserMapper.updateUser(user);
	}

	@Override
	public void deleteUser(Long userId) {
		// TODO Auto-generated method stub
		this.oauthUserMapper.deleteUser(userId);
	}

	@Override
	public void changePassword(Long userId, String newPassword) {
		// TODO Auto-generated method stub
		this.oauthUserMapper.changePassword(userId, newPassword);
	}

	@Override
	public OauthUser findOne(Long userId) {
		// TODO Auto-generated method stub
		return this.oauthUserMapper.findOne(userId);
	}

	@Override
	public List findAll() {
		// TODO Auto-generated method stub
		return this.oauthUserMapper.findAll();
	}

	@Override
	public OauthUser findByUsername(String username) {
		// TODO Auto-generated method stub
		return this.oauthUserMapper.findByUsername(username);
	}

}

4、controller层

package com.wlsq.oauth.controller;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



import com.wlsq.oauth.util.OauthUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URISyntaxException;

@RestController
public class AccessTokenController {
	@Autowired
    private OauthUtil oAuthService;

    //@Autowired
    //private IOauthUserMapperService userService;
    
    @RequestMapping("/accessToken")
    public HttpEntity token(HttpServletRequest request)
            throws URISyntaxException, OAuthSystemException {

        try {
            //构建OAuth请求
            OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);

            //检查提交的客户端id是否正确
            if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
                OAuthResponse response =
                        OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                                .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                                .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                                .buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }

            // 检查客户端安全KEY是否正确
            if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
                OAuthResponse response =
                        OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                                .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
                                .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                                .buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }

            String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
            // 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
            if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
                if (!oAuthService.checkAuthCode(authCode)) {
                    OAuthResponse response = OAuthASResponse
                            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                            .setError(OAuthError.TokenResponse.INVALID_GRANT)
                            .setErrorDescription("错误的授权码")
                            .buildJSONMessage();
                    return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
                }
            }

            //生成Access Token
            OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));


            //生成OAuth响应
            OAuthResponse response = OAuthASResponse
                    .tokenResponse(HttpServletResponse.SC_OK)
                    .setAccessToken(accessToken)
                    .setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
                    .buildJSONMessage();

            //根据OAuthResponse生成ResponseEntity
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));

        } catch (OAuthProblemException e) {
            //构建错误响应
            OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                    .buildJSONMessage();
            return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
        }
    }


}

package com.wlsq.oauth.controller;

import java.net.URISyntaxException;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;

import com.wlsq.oauth.pojo.OauthUser;

import com.wlsq.oauth.service.IOauthClientMapperService;
import com.wlsq.oauth.service.IOauthUserMapperService;
import com.wlsq.oauth.util.OauthUtil;


@Controller
public class AuthorizeController {
	@Autowired
    private OauthUtil oAuthService;

	@Resource
    private IOauthClientMapperService oauthClientService;
    
    @Autowired
    private IOauthUserMapperService userService;
    
    @RequestMapping("/authorize")
    public Object authorize(
            Model model,
            HttpServletRequest request)
            throws URISyntaxException, OAuthSystemException {

        try {
            //构建OAuth 授权请求
            OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

            //检查传入的客户端id是否正确
            if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
                OAuthResponse response =
                        OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                                .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                                .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                                .buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }


            //Subject subject = SecurityUtils.getSubject();
            //如果用户没有登录,跳转到登陆页面
           // if(!subject.isAuthenticated()) {
                if(!login(request)) {//登录失败时跳转到登陆页面
                    model.addAttribute("client", oauthClientService.findByClientId(oauthRequest.getClientId()));
                    return "oauth2login";
                }
           // }

           // String username = (String)subject.getPrincipal();
              String username =(String)request.getParameter("username");
            //生成授权码
            String authorizationCode = null;
            //responseType目前仅支持CODE,另外还有TOKEN
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            if (responseType.equals(ResponseType.CODE.toString())) {
                OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
                authorizationCode = oauthIssuerImpl.authorizationCode();
                oAuthService.addAuthCode(authorizationCode, username);
            }

            //进行OAuth响应构建
            OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
                    OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
            //设置授权码
            builder.setCode(authorizationCode);
            //得到到客户端重定向地址
            String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

            //构建响应
            final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

            //根据OAuthResponse返回ResponseEntity响应
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(new URI(response.getLocationUri()));
            return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
        } catch (OAuthProblemException e) {

            //出错处理
            String redirectUri = e.getRedirectUri();
            if (OAuthUtils.isEmpty(redirectUri)) {
                //告诉客户端没有传入redirectUri直接报错
                return new ResponseEntity("OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
            }

            //返回错误消息(如?error=)
            final OAuthResponse response =
                    OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
                            .error(e).location(redirectUri).buildQueryMessage();
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(new URI(response.getLocationUri()));
            return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
        }
    }
    //用户登入方法
    private boolean login(HttpServletRequest request) {
        if("get".equalsIgnoreCase(request.getMethod())) {
            return false;
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return false;
        }
        OauthUser user=userService.findByUsername(username);
       // UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            if(user != null){
            	return true;
            }
            return false;
           
        } catch (Exception e) {
            request.setAttribute("error", "登录失败:" + e.getClass().getName());
            return false;
        }
    }

}


package com.wlsq.oauth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.wlsq.oauth.pojo.OauthClient;
import com.wlsq.oauth.service.IOauthClientMapperService;

@Controller
@RequestMapping("/client")
public class ClientController {

    @Autowired
    private IOauthClientMapperService clientService;

    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("clientList", clientService.findAll());
        return "client/list";
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        model.addAttribute("client", new OauthClient());
        model.addAttribute("op", "新增");
        return "client/edit";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(OauthClient client, RedirectAttributes redirectAttributes) {
        clientService.createClient(client);
        redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/client";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("client", clientService.findOne(id));
        model.addAttribute("op", "修改");
        return "client/edit";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(OauthClient client, RedirectAttributes redirectAttributes) {
        clientService.updateClient(client);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/client";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("client", clientService.findOne(id));
        model.addAttribute("op", "删除");
        return "client/edit";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        clientService.deleteClient(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/client";
    }

}


package com.wlsq.oauth.controller;

public class Constants {
	public static String RESOURCE_SERVER_NAME = "chapter17-server";
	public static final String INVALID_CLIENT_DESCRIPTION = "客户端验证失败,如错误的client_id/client_secret。";

}


package com.wlsq.oauth.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

	@RequestMapping("/")
	public String index(Model model) {
		return "index";
	}

}


package com.wlsq.oauth.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @RequestMapping(value = "/login")
    public String showLoginForm(HttpServletRequest req, Model model) {
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String error = null;
//        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
//            error = "用户名/密码错误";
//        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
//            error = "用户名/密码错误";
//        } else
        if(exceptionClassName != null) {
            error = "其他错误:" + exceptionClassName;
        }
        model.addAttribute("error", error);
        return "login";
    }


}

package com.wlsq.oauth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wlsq.oauth.pojo.OauthUser;
import com.wlsq.oauth.service.IOauthUserMapperService;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IOauthUserMapperService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("userList", userService.findAll());
        return "user/list";
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        model.addAttribute("user", new OauthUser());
        model.addAttribute("op", "新增");
        return "user/edit";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(OauthUser user, RedirectAttributes redirectAttributes) {
        userService.createUser(user);
        redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/user";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "修改");
        return "user/edit";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(OauthUser user, RedirectAttributes redirectAttributes) {
        userService.updateUser(user);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/user";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "删除");
        return "user/edit";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        userService.deleteUser(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/user";
    }


    @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
    public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "修改密码");
        return "user/changePassword";
    }

    @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.POST)
    public String changePassword(@PathVariable("id") Long id, String newPassword, RedirectAttributes redirectAttributes) {
        userService.changePassword(id, newPassword);
        redirectAttributes.addFlashAttribute("msg", "修改密码成功");
        return "redirect:/user";
    }

}


package com.wlsq.oauth.controller;

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

import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wlsq.oauth.util.OauthUtil;

@RestController
public class UserInfoController {

    @Autowired
    private OauthUtil oAuthService;

    @RequestMapping("/userInfo")
    public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
        try {

            //构建OAuth资源请求
            OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
            //获取Access Token
            String accessToken = oauthRequest.getAccessToken();

            //验证Access Token
            if (!oAuthService.checkAccessToken(accessToken)) {
                // 如果不存在/过期了,返回未验证错误,需重新验证
                OAuthResponse oauthResponse = OAuthRSResponse
                        .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                        .setRealm(Constants.RESOURCE_SERVER_NAME)
                        .setError(OAuthError.ResourceResponse.INVALID_TOKEN)
                        .buildHeaderMessage();

                HttpHeaders headers = new HttpHeaders();
                headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
                return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
            }
            //返回用户名
            String username = oAuthService.getUsernameByAccessToken(accessToken);
            return new ResponseEntity(username, HttpStatus.OK);
        } catch (OAuthProblemException e) {
            //检查是否设置了错误码
            String errorCode = e.getError();
            if (OAuthUtils.isEmpty(errorCode)) {
                OAuthResponse oauthResponse = OAuthRSResponse
                        .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                        .setRealm(Constants.RESOURCE_SERVER_NAME)
                        .buildHeaderMessage();

                HttpHeaders headers = new HttpHeaders();
                headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
                return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
            }

            OAuthResponse oauthResponse = OAuthRSResponse
                    .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME)
                    .setError(e.getError())
                    .setErrorDescription(e.getDescription())
                    .setErrorUri(e.getUri())
                    .buildHeaderMessage();

            HttpHeaders headers = new HttpHeaders();
            headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
    }
}


相关项目待补充上传

你可能感兴趣的:(深蓝计划)