ssh登录实现

工程目录

配置文件详解

Spring的applicationContext.xml文件

<span ><?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    

    <!-- 定义数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置HibernateSessionFactory工厂 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <!-- 自动扫描注解方式配置的hibernate类文件 -->
        <property name="packagesToScan">
            <list>
                <value>com.tonly.entity</value>
            </list>
        </property>
    </bean>  

    <!-- 配置Hibernate事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>  

    <!-- 配置事务传播特性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="new*" propagation="REQUIRED" />
            <tx:method name="set*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="change*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
    </tx:advice>  

      <!--  配置参与事务的类 -->
    <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* com.tonly.service.*.*(..))" />
            <!-- 切面事务归txAdvice处理,把上面我们所配置的事务管理两部分属性整合起来 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
    </aop:config>

    <!-- 自动加载构建JavaBean,直接使用注解的话可以免去配置bean的麻烦,实体类可以被自动扫描 -->
    <context:component-scan base-package="com.tonly" /> 

</beans>  </span>

Hibernate.cfg.xml文件配置

<span ><?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.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration></span>

jdbc.properties文件配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_teststudio
jdbc.username=root
jdbc.password=123

struts.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">  

<struts>
    <constant name="struts.action.extension" value="action" />
    <constant name="struts.i18n.encoding" value="utf-8"></constant>
    <constant name="struts.multipart.maxSize" value="10000000"/>  <!-- 大约10M -->

    <package name="ebuy" namespace="/" extends="struts-default">

        <action name="user_*" method="{1}" class="com.tonly.action.UserAction">
            <result name="error">login.jsp</result>
            <result name="loginSuccess">main.jsp</result>
        </action>

    </package>

</struts>   

login.jsp文件,主要实现登录(输入用户名、密码)、记住密码功能,比较简单,前台jsp页面使用bootstrap框架,界面效果如下:

用户名或密码为空:

用户名或密码不正确:

登录成功,直接跳到main.jsp页面:

前台login.jsp文件详细如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="com.tonly.entity.User"%>
<%
    if(request.getAttribute("user") == null){//说明是用户首次登录,而非服务端跳转,这时候再在cookies中进行取值操作
        String userName = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        for(int i=0; cookies!=null && i<cookies.length; i++){
            if(cookies[i].getName().equals("user")){
                userName = cookies[i].getValue().split("-")[0];
                password = cookies[i].getValue().split("-")[1];
            }
        }
        if(userName == null)
            userName = "";
        if(password == null)
            password = "";
        pageContext.setAttribute("user", new User(userName, password));//EL表达式取值范围为page request session application
    }
%>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DQA - Test Studio</title>
<link
    href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.css"
    rel="stylesheet">
<link
    href="${pageContext.request.contextPath}/bootstrap/css/bootstrap-responsive.css"
    rel="stylesheet">
<script src="${pageContext.request.contextPath}/bootstrap/js/jquery.js"></script>
<script
    src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.js"></script>
<style type="text/css">
    body {
        padding-top: 10px;
        padding-bottom: 40px;
        background-color: #D6D6D6;
    }
    .form-signin-heading {
        text-align: center;
        padding-bottom: 10;
    }
    .head{
        width:100%;
        height:200px;
    }
    .form-signin {
        max-width: 390px;
        padding: 19px 29px 0px;
        margin: 0 auto 20px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
        -moz-box-shadow: 1 1px 2px rgba(0, 0, 0, .05);
        box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
    }

    .form-signin .form-signin-heading,.form-signin .checkbox {
        margin-bottom: 10px;
    }

    .form-signin input[type="text"],.form-signin input[type="password"] {
        font-size: 12px;
        height: 13px;
        margin-bottom: 15px;
        padding: 7px 9px;
        width:100%;
    }
</style>
<script type="text/javascript">

    function resetForm(){
        $("#userName").val("");
        $("#password").val("");
    }

    function checkForm(){
        var userName = $("#userName").val();
        var password = $("#password").val();
        if(userName == ""){
            $("#error").html("Please enter username");
            return false;
        }
        if(password == ""){
            $("#error").html("Please enter password");
            return false;
        }
        return true;
    }

</script>
</head>
<body>
    <div id="head" class="head">
        <div >
            <font size=6 color="#E50914"> </font>
        </div>
        <div >
            <hr size=12 color=#E50914 width=100%>
        </div>
    </div>
    <div class="container">
        <form name="myForm" class="form-signin" action="user_login.action" method="post" onsubmit="return checkForm()">
            <h2 class="form-signin-heading">Welcome to Test Studio</h2>
            <input id="userName" name="user.userName" type="text"
                value="${user.userName }" class="input-block-level"
                placeholder="Username"> <input id="password" name="user.password"
                type="password" value="${user.password }" class="input-block-level"
                placeholder="Password"> <label class="checkbox"> <input
                id="remember" name="remember" type="checkbox" value="remember-me">Remember me
                     <font id="error" color="red">${error}</font>
            </label>
            <div  align="center">
                <button class="btn btn-default btn-primary" type="submit">Login</button>

                <button class="btn btn-default btn-primary" type="button" onclick="javascript:resetForm()">Reset</button>
            </div>
            <br>
        </form>
    </div>
</body>
</html>

详细代码实现:

首先是service服务层,结构如下:

其中UserServiceImpl的具体实现如下:

package com.tonly.service.impl;

import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.tonly.dao.BaseDao;
import com.tonly.entity.PageBean;
import com.tonly.entity.User;
import com.tonly.service.UserService;
import com.tonly.util.StringUtil;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private BaseDao<User> baseDao;

    @Override
    public User login(User user) {
        List<Object> param = new LinkedList<Object>();
        StringBuffer hql = new StringBuffer("from User u where u.userName = ? and u.password = ?");
        if (user != null) {
            param.add(user.getUserName());
            param.add(user.getPassword());
            return baseDao.get(hql.toString(), param);
        }else {
            return null;
        }
    }

}

通过@Service("userService")注解声明一个服务bean,通过@Resource注入baseDao这个bean,BaseDao的实现结构如图:

其中BaseDaoImpl的具体实现如下:

package com.tonly.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tonly.dao.BaseDao;
import com.tonly.entity.PageBean;

@Repository("baseDao")
@SuppressWarnings("all")
public class BaseDaoImpl<T> implements BaseDao<T> {

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public T get(Class<T> c, Serializable id) {
        return (T) this.getCurrentSession().get(c, id);
    }

}

BaseDaoImpl中使用了泛型注入,这样在service层可以直接通过注入basedao并传递一个类型对象的方法实现basedao中方法的继承。再来看看UserServiceImpl的具体实现:

package com.tonly.service.impl;

import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.tonly.dao.BaseDao;
import com.tonly.entity.PageBean;
import com.tonly.entity.User;
import com.tonly.service.UserService;
import com.tonly.util.StringUtil;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private BaseDao<User> baseDao;

    @Override
    public User login(User user) {
        List<Object> param = new LinkedList<Object>();
        StringBuffer hql = new StringBuffer("from User u where u.userName = ? and u.password = ?");
        if (user != null) {
            param.add(user.getUserName());
            param.add(user.getPassword());
            return baseDao.get(hql.toString(), param);
        }else {
            return null;
        }
    }

}

这里直接通过@Resource注入baseDao并传递泛型参数"User",这样可以直接使用baseDao.get(hql.toString(), param)方法获取对象。

最后记录下UserAction的具体实现:

package com.tonly.action;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.tonly.entity.User;
import com.tonly.service.UserService;

@Controller
public class UserAction extends ActionSupport implements ServletRequestAware{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private HttpServletRequest request;
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    @Resource
    private UserService userService;
    private String error;
    private User user;
    private String remember;

    public String getRemember() {
        return remember;
    }
    public void setRemember(String remember) {
        this.remember = remember;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    public String getError() {
        return error;
    }
    public void setError(String error) {
        this.error = error;
    }

    public String login() throws Exception{
        HttpSession session = request.getSession();
        User currentUser = userService.login(user);
        if (currentUser == null) {
            request.setAttribute("user",user);
            error = "incorrect username or password";
            return ERROR;
        }else {
            if ("remember-me".equals(remember)) {
                remember(currentUser, ServletActionContext.getResponse());
            }
            session.setAttribute("currentUser", currentUser);
            return "loginSuccess";
        }
    }

    private void remember(User user, HttpServletResponse response) throws Exception{
        Cookie cookie = new Cookie("user", user.getUserName()+"-"+user.getPassword());
        cookie.setMaxAge(1*60*60*24*7);//设置有效期一周
        response.addCookie(cookie);
    }

}

实体User类具体代码如下:

package com.tonly.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_user")
public class User {

    private int id;
    private String userName;
    private String password;
    private String sex;
    private String email;
    private String mobile;
    private String address;
    private int status = 1; //普通用户为1,管理员为2

    public User() {
        super();
    }
    public User(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    @Id
    @GeneratedValue(generator="_native")
    @GenericGenerator(name="_native",strategy="native")
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Column(length=20)
    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;
    }

}

整个业务逻辑是:

前台login.jsp登录请求user_login.action,通过struts的OGNL方式直接将userName、password自动封装到后台action中的User对象,登录操作之后返回一个currentUser对象(用户名或密码不正确则对象为空),如果为空,则将当前User对象(前台传过来的错误User对象)置于request范围中,这样可以直接在前台通过value="${user.userName}或password="${user.password}""的方式直接回显数值。如果登录成功则再判断有没有勾选"Remember me",如果勾选则表示要求记住密码,则将当前登录成功的currentUser对象置入cookie中,这样前台脚本中可以通过判断再次取值的方式实现记住密码。

时间: 2024-08-24 03:46:43

ssh登录实现的相关文章

华为交换机配置telnet和SSH登录设备(简单实用版)

Telnet是Internet远程登陆服务的标准协议和主要方式.它为用户提供了在本地计算机上完成远程主机工作的能力.在终端使用者的电脑上使用telnet程序,用它连接到服务器.终端使用者可以在telnet程序中输入命令,这些命令会在服务器上运行,就像直接在服务器的控制台上输入一样.可以在本地就能控制服务器.要开始一个telnet会话,必须输入用户名和密码来登录服务器.Telnet是常用的远程控制Web服务器的方法,极大的提高了用户操作的灵活性. 测试拓扑图 配置telnet: 1.1普通认证登录

CentOS禁用本地root和远程ssh登录

某天为解决su切换慢的问题,黄哥修改了一个加载脚本,导致普通用户无法切换root用户,su输入密码后登录还是普通用户.当初设置禁止root登录时,未给某个特定用户增加sudo权限,导致现在所有程序无法使用(telnet服务同样被禁止了).最后通过将该系统盘挂载到另外一台服务器上,将脚本改回为原来状态解决问题. 正常后登录服务器检查CentOS使用版本为6.4,因数据安全要禁用root本地和远程ssh登录,只给普通用户权限. 禁止root本地登录 修改配置/etc/pam.d/login,增加如下

好记心不如烂笔头,ssh登录 The authenticity of host 192.168.0.xxx can&#39;t be established. 的问题

The authenticity of host 'git.coding.net (123.59.85.184)' can't be established.RSA key fingerprint is SHA256:jok3FH7q5LJ6qvE7iPNehBgXRw51ErE77S0Dn+Vg/Ik.Are you sure you want to continue connecting (yes/no)? 用ssh登录一个机器(换过ip地址),提示输入yes后,屏幕不断出现y,只有按ctr

ssh登录 The authenticity of host 192.168.0.xxx can&#39;t be established. 的问题

scp免密码登录:Linux基础 - scp免密码登陆进行远程文件同步 执行scp一直是OK的,某天在本地生成了公钥私钥后,scp到某个IP报以下错误 The authenticity of host '192.168.233.137 (192.168.233.137)' can't be established. ECDSA key fingerprint is SHA256:EsqTfeCJ34DnGV66REuRRPhoFwaLuee5wxFgEAZ8b9k. Are you sure y

【随笔】ssh登录时如何直接在参数中加入登录密码

如同apt-get安装程序时会有-y参数来避免交互输入一样,我也希望在ssh登录时能够直接附加登录密码以避免交互式输入密码这一步,网上找了找,方法很多. 比如直接通过密钥免密码登录,不过需要改动很多,感觉很麻烦.这里更想要的是不改动server/client的配置下直接免交互式ssh登录. 于是我先查看帮助: 这里没有可用参数能够附加登录密码,于是继续找办法. sshpass sshpass: 用于非交互的ssh 密码验证 ssh登陆不能在命令行中指定密码,也不能以shell中随处可见的,ssh

SSH登录缓慢的原因安在?

ssh登录异常缓慢,必须解决 ssh 192.168.120.29The authenticity of host '192.168.120.29 (192.168.120.29)' can't be established.RSA key fingerprint is 4b:13:95:c9:c8:5c:e9:6e:e5:97:80:37:1b:2e:92:f6.Are you sure you want to continue connecting (yes/no)? yesWarning:

ssh登录异常缓慢,必须解决

ssh 192.168.120.29 The authenticity of host '192.168.120.29 (192.168.120.29)' can't be established. RSA key fingerprint is 4b:13:95:c9:c8:5c:e9:6e:e5:97:80:37:1b:2e:92:f6. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanentl

shell脚本精华----在10秒内SSH登录失败次数超过3次就使用iptables/tcpwrappers拒绝

#!/bin/bash while true do badip=$(lastb -i -a | awk '/ssh:notty/ {print $NF}'|sort|uniq -c|awk '($1>3) {print $2}') for i in $badip do iptables -t filter -I INPUT -s $i -p tcp --dport 22 -j DROP done : > /var/log/btmp sleep 10s done shell脚本精华----在10

ssh登录

在Linux或者类linux系统下, root用户的权限很高,所以一般黑客采用字典攻击的方式来获得root的密码,从而进行一些的破坏动作. 所以一般采用如下的两种方式来避免针对root的字典攻击. 1 <br> 禁止通过ssh来登录root.通过修改文件 /etc/ssh/sshd_config  #PermitRootLogin yes 将其改为 PermitRootLogin no 允许root 通过 ssh登录,但是只能通过rsa key的方式修改 /etc/ssh/sshd_confi

Delphi能通过SSH登录Linux,连接MYSQL取数么?像Navicat一样

百度随时就能搜,你就懒得搜下.http://tieba.baidu.com/p/671327617 Ssh tunnel通常能实现3种功能1) 加密网络传输2) 绕过防火墙3) 让位于广域网的机器连接到局域网内的机器 --------------------------------------------------------------------------------- Delphi能通过SSH登录Linux,连接MYSQL取数么? SSH是远程连接Linux的其中一种通道方式.目前Li