Spring MVC 4 + Spring Security 4 + Hibernate +JPA实战

最近花了有三个星期把spring实战学了遍,同时也把maven,git,Hibernate给用上了,确实比较锻炼手。登陆,注册(我前端不是很好)是网上找得模版,(提前说下界面做的很挫,是用来练手的,还有很多写的不是很好的代码,我会慢慢完善的,但功能是全的)

这里写图片描述

登陆之后
这里写图片描述
用来报名考试用的
之后
这里写图片描述
点了之后,就会扣除你的钱,你也会报名成功。如果不成功就会跳转

这里写图片描述

第一步pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mine</groupId>
  <artifactId>myweb2</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>myweb2 Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <kotlin.version>1.0.5-2</kotlin.version>
  </properties>


  <dependencies>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.4.RELEASE</version>
      </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.3.4.RELEASE</version>
      </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.0.0.GA</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>





    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>1.4.2.RELEASE</version>
    </dependency>




    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.2.0.Final</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.11.Final</version>
    </dependency>





    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>



    <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>3.0.1</version>
      </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.11.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->






    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->



    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.5</version>
    </dependency>
      <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.6</version>
      </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-core</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>



    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-neo4j</artifactId>
      <version>4.1.5.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.10.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <version>3.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-mongodb</artifactId>
      <version>1.9.5.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.7.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-acl -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-acl</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>


    <dependency>
      <groupId> org.apache.cassandra</groupId>
      <artifactId>cassandra-all</artifactId>
      <version>0.8.1</version>

      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
        </exclusion>
      </exclusions>

    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib</artifactId>
      <version>${kotlin.version}</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-test</artifactId>
      <version>${kotlin.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>myweb2</finalName>
    <plugins>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>test-compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>testCompile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

第二步配置视图解析器

@Configuration
@EnableRedisRepositories("Repository")
public class ViewConfiguration {
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        return resolver;
    }


}

第三步配置spring安全

package Configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import service.UserLoginService;

import javax.sql.DataSource;

/**
 * Created by wang on 16/12/5.
 */
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = {UserLoginService.class,EntitymanagerFactoryBeanConfiguration.class})
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
    @Autowired
    DataSource dataSource;

    @Autowired
    private UserLoginService userLoginService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
       http.authorizeRequests().regexMatchers("/login/\\S+").access("hasRole('ROLE_USER') or IS_AUTHENTICATED_REMEMBERED")
               .regexMatchers("register/\\S+").access("hasRole('ROLE_USER') or IS_AUTHENTICATED_REMEMBERED")
       .and().formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/login/success")
       .and().logout().logoutSuccessUrl("/login");


    }


    @Autowired
    public void  configureGlobalSecurity(AuthenticationManagerBuilder auth)throws Exception{
        System.out.println("cG");
        /*这个Service会在后面重写*/
       auth.userDetailsService(userLoginService);

    }


}
package Configuration;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
 * Created by wang on 16/12/5.
 */
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{


}

第五步继续配置安全,不过是同过继承UserDetails来封装user的信息,这段代码可以在看完user之后再看

package service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * Created by wang on 16/12/7.
 */
public class UserRealDetails implements UserDetails{
    private List<GrantedAuthority> authorityList;
    private String Password;
    private String Username;
    private boolean isAccountNonExpired;
    private boolean isAccountNonLocked;
    private boolean isCredentialsNonExpired;
    private String email;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    private int remaingMoney;
    private boolean enalbel;
    private long id;

    public UserRealDetails(List<GrantedAuthority> authorityList, boolean enalbel,String password, String username, boolean isAccountNonExpired, boolean isAccountNonLocked, boolean isCredentialsNonExpired, String email, String firstName, String lastName, String phoneNumber,int remaingMoney,long id) {
        this.authorityList = authorityList;
        Password = password;
        Username = username;
        this.isAccountNonExpired = isAccountNonExpired;
        this.isAccountNonLocked = isAccountNonLocked;
        this.isCredentialsNonExpired = isCredentialsNonExpired;
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.phoneNumber = phoneNumber;
        this.enalbel =enalbel;
        this.remaingMoney = remaingMoney;
        this.id=id;
    }

    public long getId() {
        return id;
    }

    public int getRemaingMoney() {
        return remaingMoney;
    }

    public String getEmail() {
        return email;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorityList;
    }

    @Override
    public String getPassword() {
        return Password;
    }

    @Override
    public String getUsername() {
        return Username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return isAccountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return isAccountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return isCredentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enalbel;
    }


}

这是之前提到的serviece,这是自定义的验证的服务

package service;

import Dao.UserDao;
import Domin.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wang on 16/12/6.
 */
@Service
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan({"Dao","Configuration"})
public class UserLoginService implements UserDetailsService{
    @Autowired
    private UserDao userDao;


    @Cacheable("User")
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByUserName(username);
        System.out.println("User"+user);
        if (user==null){
            System.out.println("User not found");
            throw new UsernameNotFoundException("UserName not found");
        }


       return new UserRealDetails(getGrantedAuthorities(user),user.getEnable().equals("true"),user.getPassWord(),user.getUserName(),
                true,true,true,user.getEmail(),user.getFirstName(),
                user.getLastName(),user.getPhoneNumber(),user.getRemainingMoney(),user.getId());
    }
    private List<GrantedAuthority> getGrantedAuthorities(User user){
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(user.getAuthorityTable().getUserAuth()));
        return authorities;
    }
}

第六步用来,建立表单,这里可以学一对一,一对多,多对多的例子(楼主表单名字没起好,学生成绩的表单和专门放科目的表单名字不易区分,后期维护肯定难)

@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotNull
    @Column(name = "userName", nullable = true, unique = true, length = 30)
    private String userName;

    @NotNull
    @Column(name = "passWord", nullable = true, length = 30)
    private String passWord;
    @Column
    private int RemainingMoney;

    @NotNull

    @Column(name = "phoneNumber", nullable = true, length = 20)
    private String phoneNumber;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "studentId")
    private List<Studentscore> scoreTable;

    @NotNull
    @Column(name = "email", nullable = true, unique = true, length = 50)
    private String email;
    @NotNull
    @Column(name = "lastName", nullable = true, length = 20)
    private String lastName;
    @NotNull
    @Column(name = "firstName", nullable = true, length = 20)
    private String firstName;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "User_Table", joinColumns = {@JoinColumn(name = "id")},
            inverseJoinColumns = {@JoinColumn(name = "TABLE_ID")})
    private List<scoreTable> table;

    @Column(name = "enable")
    private String enable;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "authId")
    private AuthorityTable authorityTable;

    public AuthorityTable getAuthorityTable() {
        return authorityTable;
    }

    public void setAuthorityTable(AuthorityTable authorityTable) {
        this.authorityTable = authorityTable;
    }

    public List<Studentscore> getScoreTable() {
        return scoreTable;
    }

    public void setScoreTable(List<Studentscore> scoreTable) {
        this.scoreTable = scoreTable;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(id).toHashCode();
    }

    public String getEnable() {
        return enable;
    }

    public void setEnable(String enable) {
        this.enable = enable;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        User user = (User) obj;
        return new EqualsBuilder().appendSuper(super.equals(obj))
                .append(id, user.id).isEquals();
    }

    public int getRemainingMoney() {
        return RemainingMoney;
    }

    public void setRemainingMoney(int remainingMoney) {
        RemainingMoney = remainingMoney;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }


    public List<scoreTable> getTable() {
        return table;
    }

    public void setTable(List<scoreTable> table) {
        this.table = table;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
@Entity
@Table(name = "student_score")
public class Studentscore {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String courseName;

    private String score;


    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }
}
package Domin;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

/**
 * Created by wang on 16/12/2.
 */
@Entity
@Table(name = "score")
public class scoreTable implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "TABLE_ID")
    private int id;

    @ManyToMany(mappedBy = "table",fetch = FetchType.EAGER)
    private List<User> list;

    private String courseName;

    private int price;


    public List<User> getList() {
        return list;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setList(List<User> list) {
        this.list = list;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17,37).append(id).toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null){return  false;}
        if (obj == this){return true;}
        if (obj.getClass()!=getClass()){
            return false;
        }
        scoreTable table = (scoreTable) obj;
        return new EqualsBuilder()
                .append(id,table.getId()).isEquals();
    }
}
package Domin;

import javax.persistence.*;

/**
 * Created by wang on 16/12/5.
 */
@Entity
@Table(name = "auth")
public class AuthorityTable {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private int id;
   @OneToOne(mappedBy = "authorityTable")
    private User user;
   @Column
    private String userAuth;

    public long getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getUserAuth() {
        return userAuth;
    }

    public void setUserAuth(String userAuth) {
        this.userAuth = userAuth;
    }
}

第七步,建立dao层(没有service层,多了一层Repository层),这里会用到spring data jpa

public interface UserRepository extends JpaRepository<User,Integer> {
    //User findByuserName(String username);

    User saveAndFlush(User entity);
    List<User> findByFirstName(String firstName);
    User findByUserName(String userName);
    User findByEmail(String email);
    List<User> findByLastName(String lastName);
    User findById(long id);
//    List<scoreTable> findTable(long id);

    @Query("select t.scoreTable from  Domin.User t where t.id =?1")
    List<Studentscore> getByScoreTable(long id);

    @Modifying
    @Query(value = "update Domin.User t set t.firstName = ?1 where t.id = ?2")
    void updateFirstName(String newFirstName,long id);
    @Modifying
    @Query(value = "update Domin.User t set t.lastName= ?1 where t.id=?2")
    void updateLastName(String newLastname,long id);
    @Modifying
    @Query(value = "update Domin.User t set t.passWord=?1 where t.id = ?2")
    void updatePassWord(String newPassWord,long id);
    @Query("select t.table from Domin.User t  where t.id=?1 ")
    List<scoreTable> findscoreTable(long id);
    @Modifying
    @Query(value = "update Domin.User t set  t.table = ?1 where t.id = ?2")
    void updateScoreTable(List<scoreTable> newList, long id);
    @Modifying
    @Query(value = "update Domin.User as t set t.RemainingMoney = ?1 where t.id = ?2")
    void updateRemainningMoney(int newMoney,long id);

}

有些数据库的改动,jpa我实在想不到怎么改了,都是异常。最后只能先妥协用这种方法

@Repository
@ComponentScan(basePackageClasses = EntitymanagerFactoryBeanConfiguration.class)
@Transactional
public class UserDao {
   @Autowired
    private UserRepository userRepository;

   @Autowired
   private CourseDao courseDao;
   @PersistenceContext
    private EntityManager entityManager;

    public User findByid(long id){
        return  userRepository.findById(id);
    }
    @Transactional
    public User save(User user){
        return userRepository.save(user);
    }
    @Transactional
    public User findByUserName(String userName){
        return userRepository.findByUserName(userName);
    }
    @Transactional
    public List<User> fingbyFirstName(String firstName){
        return userRepository.findByFirstName(firstName);
    }
    @Transactional
    public List<User> findbyLastName(String lastName){
        return userRepository.findByLastName(lastName);
    }
    @Transactional
    public User findbyEmail(String email){
        return userRepository.findByEmail(email);
    }
    @Transactional
    public void updataFirstName(String newFirstName,int id){
        userRepository.updateFirstName(newFirstName,id);
    }
    @Transactional
    public void updateLastName(String newLastName,int id){
        userRepository.updateLastName(newLastName,id);
    }
    @Transactional
    public void updatePassWord(String newpassWord , int id){
        userRepository.updatePassWord(newpassWord,id);
    }
    @Transactional
    public List<scoreTable> findScoreTableById(long id){
        return userRepository.findscoreTable(id);
    }

    @Transactional
    public List<Studentscore> findStudentScoreTable(long id){
        return userRepository.getByScoreTable(id);
    }
    @Transactional
    public void updateAllTable (List<scoreTable> newTable , long id){
        User user = userRepository.findById(id);
        user.getTable().add(courseDao.findCourseName("MATH"));
        user.setTable(newTable);
        entityManager.flush();
       userRepository.updateScoreTable(newTable,id);
    }
    @Transactional
    public  void addStudentScoreTable(Studentscore table,long id){
        User user = userRepository.findById(id);
        if(user.getScoreTable()!=null){
            user.getScoreTable().add(table);
        }else {
            List<Studentscore> list = new ArrayList<>();
            list.add(table);
            user.setScoreTable(list);
        }
        entityManager.persist(user);
    }
    @Transactional
    public void addscoreTable (scoreTable table,long id){
        User user=userRepository.findById(id);
        if(user.getTable()!=null){
            user.getTable().add(table);
        }else {
            List<scoreTable> list = new ArrayList<>();
            list.add(table);
            user.setTable(list);
        }
        entityManager.merge(user);
    }
    public void deleteScoreTable(scoreTable table,long id){
        User user = userRepository.findById(id);
        if(!user.getTable().remove(table)){
            throw new NoSuchElementException("没有这张成绩单");
        }

    }
    @Transactional
    public void updataRemainningMoney (int newMoney,long id){
        this.userRepository.updateRemainningMoney(newMoney,id);
    }
}
package Dao;

import Domin.scoreTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Repository;
import Repository.ScoreTableRepository;
/**
 * Created by wang on 16/12/10.
 */
@Repository
@ComponentScan("Respository")
public class CourseDao {
    @Autowired
    private ScoreTableRepository scoreTableRepository;
    public scoreTable findCourseName(String courseName){
        return scoreTableRepository.findByCourseName(courseName);
    }

}

第八步,建立控制器,登陆进去靠security,是不需要自己写控制器的

package Controller;

import Dao.CourseDao;
import Dao.UserDao;
import Domin.Studentscore;
import Domin.User;
import Domin.scoreTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import service.UserRealDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by wang on 16/12/10.
 */
@Controller
@RequestMapping("/buy/")
@ComponentScan("Dao")
public class BuyController {
    @Autowired
    private HttpSession session;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private UserDao userDao;
    @RequestMapping("course")
    public String buyCourese(@RequestParam("name") String courseName, Model model, HttpServletRequest request){
        scoreTable scoreTable = courseDao.findCourseName(courseName);
        System.out.println(scoreTable);
        model.addAttribute("scoreTable",scoreTable);
        request.getSession().setAttribute("scoreTable",scoreTable);
        System.out.println(11);
        return "pay";
    }
    @RequestMapping("success")
    public String buyEnd(@SessionAttribute UserRealDetails user, @SessionAttribute scoreTable scoreTable,Model model,HttpServletRequest request){
        int remainMoney = user.getRemaingMoney()-scoreTable.getPrice();
        User realUser = userDao.findByUserName(user.getUsername());

        if (realUser.getTable()==null||realUser.getTable().contains(scoreTable)){
            System.out.println(0);
            model.addAttribute("message","考试已经报名");
            return "pay";
        }

       if (remainMoney>0) {
            request.removeAttribute("message");
           userDao.updataRemainningMoney(remainMoney,realUser.getId());

           userDao.addscoreTable(scoreTable,realUser.getId());
           realUser.setRemainingMoney(remainMoney);

           Studentscore studentscore = new Studentscore();
           studentscore.setCourseName(scoreTable.getCourseName());
           studentscore.setScore("noScore");

           userDao.addStudentScoreTable(studentscore,realUser.getId());
           if (model.containsAttribute("user1")){
               model.asMap().put("user1",realUser);
           }else {
               model.addAttribute("user1", realUser);
           }
           return "profile";
       }
            return "makemoney";
    }
}

这是如果购买没钱,就会进入充钱的网站

package Controller;

import Dao.UserDao;
import Domin.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import service.UserRealDetails;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

/**
 * Created by wang on 16/12/14.
 */
@Controller
@RequestMapping("/")
public class MakeMoney {
    @Autowired
    private UserDao userDao;
    @RequestMapping("makemoney.do")
    @Transactional
    public String  makeMoney(String money, @SessionAttribute UserRealDetails user, HttpServletRequest request){
        User user1 = userDao.findByid(user.getId());
        int nowMoney = user1.getRemainingMoney()+Integer.valueOf(money);
        System.out.println(55);
        if (request.getSession().getAttribute("user1")!=null){
            user1.setRemainingMoney(nowMoney);
            request.getSession().setAttribute("user1",user1);
            userDao.updataRemainningMoney(nowMoney,user.getId());

            return"profile";
        }else {

            user1.setRemainingMoney(nowMoney);
            request.getSession().setAttribute("user1",user1);
            userDao.updataRemainningMoney(nowMoney,user.getId());
            return "profile";
        }
    }
}

最后是视图(模版随意用)

这是登陆页面

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: wang
  Date: 16/11/27
  Time: 上午8:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
    <meta name="keywords" content="Flat Dark Web Login Form Responsive Templates, Iphone Widget Template, Smartphone login forms,Login form, Widget Template, Responsive Templates, a Ipad 404 Templates, Flat Responsive Templates" />
    <link href="css/style.css" rel='stylesheet' type='text/css' />
    <!--webfonts-->
    <link href='http://fonts.useso.com/css?family=PT+Sans:400,700,400italic,700italic|Oswald:400,300,700' rel='stylesheet' type='text/css'>
    <link href='http://fonts.useso.com/css?family=Exo+2' rel='stylesheet' type='text/css'>
    <!--//webfonts-->
    <script src="http://ajax.useso.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script>$(document).ready(function(c) {
    $('.close').on('click', function(c){
        $('.login-form').fadeOut('slow', function(c){
            $('.login-form').remove();
        });
    });
});
</script>
<!--SIGN UP-->
<h1>klasikal Login Form</h1>
<div class="login-form">
    <div class="close"> </div>
    <div class="head-info">
        <label class="lbl-1"> </label>
        <label class="lbl-2"> </label>
        <label class="lbl-3"> </label>
    </div>
    <div class="clear"> </div>
    <div class="avtar">
        <img src="images/avtar.png" />
    </div>
    <form  method="post">

        <input type="text" name="username" class="text"  value="Username" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Username';}" />
        <div class="key">
            <input type="password" name="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}" />
        </div>
        <div class="signin">
            <input type="submit" value="Login" >
        </div>

    </form>

</div>
<div class="copy-rights">
    <p>Copyright &copy; 2015.Company name All rights reserved.More Templates <a href="http://www.cssmoban.com/" target="_blank" title=""></a> - Collect from <a href="http://www.cssmoban.com/" title="da" target="_blank">1</a></p>
</div>

</body>
</html>

这是购买首页,登陆进来后直接跳转首页

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: wang
  Date: 16/12/8
  Time: 下午9:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title></title>
    <link type="text/css" rel="stylesheet" href="/css/reset.css">
    <link type="text/css" rel="stylesheet" href="/css/1024_768.css"/>
    <link type="text/css" rel="stylesheet" media="screen and (min-width:861px) and (max-width:960px)"
          href="/css/pad_heng.css"/>
    <link type="text/css" rel="stylesheet" media="screen and (min-width:601px) and (max-width:860px)"
          href="/css/pad.css"/>
    <link type="text/css" rel="stylesheet" media="screen and (min-width:481px) and (max-width:600px)"
          href="/css/tel_heng.css"/>
    <link type="text/css" rel="stylesheet" media="screen and (max-width:480px)" href="css/tel.css"/>
</head>

<body>
<div class="w_100_l top_title">
    <div class="main">
        <p><a href="#">Buy more than one book and save big! </a><a href="#">Read more</a></p>
    </div>
</div>
<c:if test="${user==null}"><security:authentication property="principal" var="user" scope="session"/></c:if>
<div class="w_100_l">
    <div class="main">
        <div class="top_banner">
            <div class="top_logo"></div>
            <div class="top_menu">
                <ul>
                    <li class="sel"><a href="#">STORE</a></li>
                    <li><a href="/mine">HOME</a></li>



                </ul>
            </div>
            <div class="top_shop_cur"><a href="/logout"><img src="/images/logout.png" alt="shopping car"/></a></div>
        </div>
        <span class="index_img"><img src="/images/ziyuan1.jpg" border="0" usemap="#Map" width="900px"/>
        <map name="Map" id="Map">
          <area shape="rect" coords="857,230,930,269" href="#" alt="buy now"/>
        </map>
      </span>
        <p class="index_hr"></p>
        <div class="content">
            <h1 class="h1_book_title">Also from A Book Apart</h1>
            <ul>

                <li>
                    <dl>
                        <c:set value="math" var="math"/>
                        <dd><a href="#"><img src="/images/book_04.jpg" alt="book"/></a></dd>
                        <dt>
                        <p class="book_title"><a href="#" target="_blank">MATH</a></p>
                        <p class="book_inline">$100</p>
                        <a class="book_buy" href="/buy/course?name=${math}" target="_blank">SING UP</a>
                        </dt>
                    </dl>
                </li>
                <li>
                    <dl>
                        <c:set value="CET4" var="CET4"/>
                        <dd><a href="#"><img src="/images/book_05.jpg" alt="book"/></a></dd>
                        <dt>
                        <p class="book_title"><a href="#" target="_blank">CET 4</a></p>
                        <p class="book_inline">$50</p>
                        <a class="book_buy" href="/buy/course?name=${CET4}" target="_blank">SING UP</a>
                        </dt>
                    </dl>
                </li>
                <li>
                    <dl>
                        <c:set value="CET6" var="CET6"/>
                        <dd><a href="#"><img src="/images/book_06.jpg" alt="book"/></a></dd>
                        <dt>
                        <p class="book_title"><a href="#" target="_blank">CET 6</a></p>
                        <p class="book_inline">$50</p>
                        <a class="book_buy" href="/buy/course?name=${CET6}" target="_blank">SIGN UP</a>
                        </dt>
                    </dl>
                </li>
            </ul>
        </div>
        <p class="index_hr"></p>

        <p class="index_hr"></p>
        <h1 class="news_title">Newsletter</h1>
        <p class="news_title_1"><span class="span_1">Keep up to date with new book releases and announcements with our newsletter.</span><span
                class="span_2"><img src="/images/logout"/></span></p>
        <p class="index_hr" style="margin-top:20px;"></p>
        <div class="footer">
            <span class="span_1">&copy; Copyright 2014, A Book Apart, LLC</span>&nbsp;&nbsp;
            <a href="#">Help & Contact us</a>
            <a class="a1" href="#">Press Room RSS feed</a>
            <a class="a2" href="#">abookapart on Twitter</a>
            <span class="span_2"><b>Published by</b><img src="/images/icon_hg.jpg" align="absmiddle"/></span>
        </div>
    </div>
</div>
<div style="display:none">
    <script src="http://v7.cnzz.com/stat.php?id=155540&web_id=155540" language="JavaScript" charset="gb2312"></script>
</div>
</body>
</html>

这是自己的主页,有自己的信息,不是模版了,要用到很多el语言

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: wang
  Date: 16/11/27
  Time: 下午1:07
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <title>youProfile</title>
    <style type="text/css">
        h1 div.qeiSec {
            position: absolute;
            text-align: center;

        }
    </style>
</head>
<body>
<h1>欢迎回到主页</h1>

<c:if test="${user==null}"><security:authentication property="principal" var="user" scope="session"/></c:if>

<${s}
<c:if test="${user1==null}">
<div class="qeiSec">
    <div class="qeiSec1">
        <div class="0Itemb">用户姓名:<c:out value="${user.lastName}${user.firstName}"/></div>
        <div class="0Itemb">手机号码:<c:out value="${user.phoneNumber}"/></div>
        <div class="0Itemb">剩余钱财:<c:out value="${user.remaingMoney}"></c:out></div>
        <div><a href="/logout"><img src="/images/logout.png"></a><a href="/success"><img src="/images/fanhui.png"></a></div>
    </div>
</div>
</c:if>
<c:if test="${user1!=null}">
    <div class="qeiSec1">
        <div class="0Itemb">用户姓名:<c:out value="${user1.lastName}${user1.firstName}"/></div>
        <div class="0Itemb">手机号码:<c:out value="${user1.phoneNumber}"/></div>
        <div class="0Itemb">剩余钱财:<c:out value="${user1.remainingMoney}"></c:out></div>
        <div><a href="/logout"><img src="/images/logout.png"></a><a href="/success"><img src="/images/fanhui.png"></a></div>
    </div>
</c:if>
<br/>
<br/>
<c:if test="${message!=null}"><c:out value="${message}"></c:out></c:if>
<a href="/minescore"><img src="/images/chaxun.png"></a>
</body>

</html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: wang
  Date: 16/12/10
  Time: 下午2:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
书本费用:<c:out value="${scoreTable['price']} "/><br/>
<c:if test="${user1==null}">
    您的剩余钱财:<c:out value="${user.remaingMoney}"/><br/>
</c:if>
<c:if test="${user1!=null}">
    您的剩余钱财:<c:out value="${user1.remainingMoney}"/><br/>
</c:if>
<a href="/buy/success"><img src="/images/quereng.png"></a><a href="/success"><img src="/images/fanhui.png"></a>
</body>
</html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: wang
  Date: 16/12/10
  Time: 下午11:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>尊敬的客户,您的余额不足</h1>
<form action="/makemoney.do">
    <input type="text"  name="money"    />
    <input type="submit" value="提交" />;
</form>

</body>
</html>

最后还有一个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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="really.com"/>
    <context:component-scan base-package="Configuration"/>
    <context:component-scan base-package="Controller"/>
    <context:component-scan base-package="service"/>
    <context:component-scan base-package="Dao"/>
    <context:component-scan base-package="Repository"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <!--<mvc:resources mapping="/js/**" location=""/>-->
    <mvc:resources mapping="/images/**" location="/WEB-INF/pages/images/"/>
    <mvc:resources mapping="/css/**" location="/WEB-INF/pages/css/"/>
    <mvc:resources mapping="/javascript/**" location="/WEB-INF/pages/Js/"/>
    <mvc:default-servlet-handler />

</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <display-name>SpringMVCDemo Web Application</display-name>

    <servlet>
      <servlet-name>mvc-dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvcdispatcher-servelt.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
      <servlet-name>mvc-dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>



</web-app>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值