1

Я запутался какая мог быть у меня ошибка? Вот и покажу их hibernate.cfg.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost/devdb</property>
        <property name="hibernate.connection.username">devdbuser</property>
        <property name="hibernate.connection.password">postgres</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Контроллер :

@Controller
@SessionAttributes("users")
public class HomeController {

    private static Logger log = LoggerFactory.getLogger(HomeController.class);


    @Inject
    private BookDAO bookDAO;

    @Inject
    @Autowired
    private UsersDAO usersDAO;

    @Autowired
    @Inject
    private UsersDAOService usersDAOService;

    @RequestMapping(method = RequestMethod.GET, value = {"/", "/home"})
    public String showHomePage(ModelAndView mv) {
        log.info("Hit controller");


        return "home";
    }


    @RequestMapping(method = RequestMethod.POST, value = "/listUsers")
    public ModelAndView viewUsers(ModelAndView mview) {
        log.info("Userlarga o'tdi");
        List<Users> usersList = usersDAO.getAllUserData();
        return new ModelAndView("usersList", "userLIST", usersList);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/regForm")
    public String regForm(ModelAndView mview) {
        log.info("Registraсiya");
        return "regForm";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/listbooks")
    public String listBooks(Model model) {
        List<Book> books = bookDAO.getAllBooks();
        model.addAttribute("books", books);
        return "listResults";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getbook")
    public String getBook(String title, Model model) {

        List<Book> books = bookDAO.getBooksByTitle(title);
        model.addAttribute("books", books);
        return "listResults";
    }


    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    public String uploadFile(String description, @RequestParam(value = "myFile") MultipartFile uploadedFile, Model model) {

        Long fileSize = uploadedFile.getSize();
        log.info("File size received = " + fileSize);
        log.info("Description = " + description);

        model.addAttribute("desc", description);
        model.addAttribute("fileSize", fileSize);
        return "uploadSuccess";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/addUser")
    public String addUser(@ModelAttribute("userAdded") Users users, ModelMap modelMap) {  // ModelAndView

        modelMap.addAttribute("userName", users.getUserName());
        modelMap.addAttribute("userFam", users.getUserFam());
        modelMap.addAttribute("userLogin", users.getUserLogin());
        modelMap.addAttribute("userPass", users.getUserPass());
        modelMap.addAttribute("userEmail", users.getUserEmail());
        modelMap.addAttribute("userAge", users.getUserAge());

        if (users.getUserName() != null && users.getUserAge() > 7 && users.getUserEmail() != null && users.getUserFam() != null && users.getUserLogin() != null && users.getUserPass() != null) {

            usersDAOService.insertUser(users);
        } else {
            System.out.println("Qatorlarni to'liq to'ldiring!");
            return "regForm";
        }
        return "success";
    }

    @RequestMapping(value = "/delete/{userId}", method = RequestMethod.POST) 
    public ModelAndView deleteUser(@PathVariable(value="userId") Integer userId, Users users ) throws NotFoundException{ //Integer userid

        ModelAndView modelAndView = new ModelAndView("usersList");
        try {
            usersDAOService.delUser(userId);
            String delMessage = "User by id number is " + usersDAOService.getUsersById(users.getUserId()) + " was succesfully removed";
            modelAndView.addObject("message", delMessage);
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("This user is does not deleted, try later!");
            return new ModelAndView("usersList");
        }
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/update/{userid}")   //method = RequestMethod.PUT, value =
    public String updateUser(@ModelAttribute Users users) {
        usersDAOService.updateUser(users);
        return "usersList";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/edit/{userid}")     
    public String editUser(@RequestParam(value = "userid", required = true) Integer id, @ModelAttribute Users users, ModelMap modelMap) {

        if (true) {

            Users usersObject = usersDAOService.getUsersById(id);

            return "Edit" + usersObject;
        } else {
            return "usersList";
        }
    }

  }

И мой user list :

<div class="orta">

    <table class="tabList2" border="1px">
        <tr>
            <td>Id</td>


            <td>Login</td>

            <td>Password</td>

            <td>User name</td>

            <td>Last name</td>

            <td>Email</td>

            <td>Age</td>

            <td>Update</td>
            <td>Delete</td>
            </tr>
        <c:if test="${!empty userLIST}">
            <c:forEach var="users" items="${userLIST}">
                <tr>
                    <td><c:out value="${users.userId}"/></td>
                    <td><c:out value="${users.userLogin}"/></td>
                    <td><c:out value="${users.userPass}"/></td>
                    <td><c:out value="${users.userName}"/></td>
                    <td><c:out value="${users.userFam}"/></td>
                    <td><c:out value="${users.userEmail}"/></td>
                    <td><c:out value="${users.userAge}"/></td>

                    <td>
                        <form method="post" action="/edit">
               <input type="submit" class="update_Delete" value="Update"/>
                        </form>
                    </td>
                    <td>
                        <form name="userId" action="/delete/?id=${users.userId}" method="POST" target="_blank">
                <input type="submit" class="update_Delete" value="DELETE" />
                              </form>
                    </td>  
                </tr>
            </c:forEach>
        </c:if>
    </table>
      </div>

servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
    default-autowire="byName">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Enables proper handling of multipart post requests such as file uploads -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10000000" />
    </bean>

    <!-- Enable rendering of JSON back to client -->
    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="text/xml" />
                <entry key="htm" value="text/html" />
            </map>
        </property>
        <property name="favorParameter" value="true" />
        <property name="favorPathExtension" value="false" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="defaultContentType" value="application/json" />
    </bean>

    <context:component-scan base-package="com.force.samples" />

    <!-- Persistence infrastructure -->
    <tx:annotation-driven />

    <!-- Drives transactions using local JPA APIs -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="exampleHibernateJPA" />
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <!-- DAO configs -->
    <bean id="usersDAO" class="com.force.samples.dao.UsersDAOImpl" />
    <bean id="usersDAOService" class="com.force.samples.dao.UsersDAOServiceImpl" />

</beans>

Дает ошибку

HTTP Status 404 - type Status report message description The requested resource is not available.

и на идее вот так:

WARN : org.springframework.web.servlet.PageNotFound | No mapping found for HTTP request with URI [/edit] in DispatcherServlet with name 'appServlet'

или

WARN : org.springframework.web.servlet.PageNotFound | No mapping found for HTTP request with URI [/delete/] in DispatcherServlet with name 'appServlet'

Заранее спасибо вам всем за внимание!

3
  • А Insert (add user) и Select работает нормально, здесь может только url адрес неправильно указана, а если так, тогда как мне его правильно писать? Commented 20 апр. 2016 в 10:16
  • 2
    В jsp выводить url-ы так ${request.contextPath}/delete или ${pageContext.request.contextPath}/delete чтобы в html получилась ссылка вида /web-app-name/delete вместо /delete. Когда /delete браузер обращается к адресу http(s)://server:port/delete, Но Вам очевидно надо http(s)://server:port/web-app-name/delete
    – Sergey
    Commented 20 апр. 2016 в 10:28
  • Спасибо Сергей! что помогали мне. Теперь идет на контроллер, получается Commented 20 апр. 2016 в 12:36

1 ответ 1

1

Я использовал ${pageContext.request.contextPath}/delete/?userId=${users.userId} и метод удаления

 @RequestMapping(value = "/delete", method = RequestMethod.POST) 
public ModelAndView deleteUser(Integer userId) throws NotFoundException{ 

    ModelAndView modelAndView = new ModelAndView("usersList");
    try {
        usersDAOService.delUser(userId);            
        return modelAndView;

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("This user is does not deleted, try later!");
        return new ModelAndView("usersList");
    }
} 

и все, спасибо вам большое!

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.