在maven项目中映射错误

时间:2017-04-17 17:10:51

标签: jersey

我在宁静的应用程序和maven中非常新。我试图使用hibernate在maven中创建一个web动态项目应用程序。但我面临404错误问题。我认为问题出在我的web.xml文件中。如果有人能提供帮助我真的很感激。以下是我的完整代码。

MyResource.java

import com.crud.dao.EmployeeDAO;


@Path("/employees")
public class MyResource {

    @GET
    @Produces("application/json")
    public List<Employee> getEmployee() {
        EmployeeDAO dao = new EmployeeDAO();
        List employees = dao.getEmployees();
        return employees;
    }


    @POST
    @Path("/create")
    @Consumes("application/json")
    public Response addEmployee(Employee emp){
        emp.setName(emp.getName());
        emp.setAge(emp.getAge());

        EmployeeDAO dao = new EmployeeDAO();
        dao.addEmployee(emp);

        return Response.ok().build();
    }

    @PUT
    @Path("/update/{id}")
    @Consumes("application/json")
    public Response updateEmployee(@PathParam("id") int id, Employee emp){
        EmployeeDAO dao = new EmployeeDAO();
        int count = dao.updateEmployee(id, emp);
        if(count==0){
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
        return Response.ok().build();
    }

    @DELETE
    @Path("/delete/{id}")
    @Consumes("application/json")
    public Response deleteEmployee(@PathParam("id") int id){
        EmployeeDAO dao = new EmployeeDAO();
        int count = dao.deleteEmployee(id);
        if(count==0){
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
        return Response.ok().build();
    }
}

Employee.java

package com.crud.dao;

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

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    @Column
    private String name;
    @Column
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

EmployeeDAO.java

public class EmployeeDAO {

    public void addEmployee(Employee bean){
        Session session = SessionUtil.getSession();        
        Transaction tx = session.beginTransaction();
        addEmployee(session,bean);        
        tx.commit();
        session.close();

    }

    private void addEmployee(Session session, Employee bean){
        Employee employee = new Employee();

        employee.setName(bean.getName());
        employee.setAge(bean.getAge());

        session.save(employee);
    }

    public List<Employee> getEmployees(){
        Session session = SessionUtil.getSession();    
        Query query = session.createQuery("from Employee");
        List<Employee> employees =  query.list();
        session.close();
        return employees;
    }

    public int deleteEmployee(int id) {
        Session session = SessionUtil.getSession();
        Transaction tx = session.beginTransaction();
        String hql = "delete from Employee where id = :id";
        Query query = session.createQuery(hql);
        query.setInteger("id",id);
        int rowCount = query.executeUpdate();
        System.out.println("Rows affected: " + rowCount);
        tx.commit();
        session.close();
        return rowCount;
    }

    public int updateEmployee(int id, Employee emp){
         if(id <=0)  
               return 0;  
         Session session = SessionUtil.getSession();
            Transaction tx = session.beginTransaction();
            String hql = "update Employee set name = :name, age=:age where id = :id";
            Query query = session.createQuery(hql);
            query.setInteger("id",id);
            query.setString("name",emp.getName());
            query.setInteger("age",emp.getAge());
            int rowCount = query.executeUpdate();
            System.out.println("Rows affected: " + rowCount);
            tx.commit();
            session.close();
            return rowCount;
    }
}

SessionUtil.java

package com.crud.dao;

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

public class SessionUtil {

    private static SessionUtil instance=new SessionUtil();
    private SessionFactory sessionFactory;

    public static SessionUtil getInstance(){
            return instance;
    }

    private SessionUtil(){
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        sessionFactory = configuration.buildSessionFactory();
    }

    public static Session getSession(){
        Session session =  getInstance().sessionFactory.openSession();

        return session;
    }
}

的web.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.22.1 2015-10-07 10:54:41"/>
    <doc xmlns:jersey="http://jersey.java.net/" jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8080/jersey-webapp/webapi/application.wadl?detail=true"/>
    <grammars/>
    <resources base="http://localhost:8080/jerseypro/webapi/">
        <resource path="/employees">
            <method id="getEmployee" name="GET">
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
        </resource>
    </resources>
    <servlet>
        <servlet-name>jerseypro</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!-- Define the ResourceConfig class -->
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.crud.jerseypro.MyResource</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Pro</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</application>

的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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>jersey</groupId>
  <artifactId>jerseypro</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jerseypro</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
  </dependencies>
  <build>
  <plugins>
  <plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.1.1</version>
  <executions>
  <execution>
  <phase>
  Employee
  </phase>
  <goals>
  <goal>java</goal>
  </goals>
  <configuration>
  <mainClass>com.crud.dao.Employee</mainClass>
  <arguments>
  <argument>
  myArg1
  </argument>
  <argument>myArg2</argument>
  </arguments>
  </configuration>
  </execution>
  </executions>
  </plugin>
  </plugins>
  </build>
</project>

提前谢谢!

1 个答案:

答案 0 :(得分:1)

一个显而易见的事情是你的servlet映射不正确。

<servlet>
        <servlet-name>jerseypro</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!-- Define the ResourceConfig class -->
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.crud.jerseypro.MyResource</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Pro</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>

您的servlet名称为jerseypro,但您的servlet映射已映射到Jersey Pro。这应该在启动时给你一个错误。检查您的java日志以查看发生了什么。

此外,您的maven项目配置无效。看起来它将尝试启动Employee类,但该类没有静态main方法。这也行不通。查看tomcat7 maven插件。它将启动一个http服务器来托管您的球衣代码以进行测试。您可以使用mvn tomcat7:run启动它。这应该让你去。