【问题标题】:SPRING 3.0 MVC 2 page 1 controllerSPRING 3.0 MVC 2 页 1 控制器
【发布时间】:2014-02-28 17:20:56
【问题描述】:

我只想在JAVA Spring 3.0 MVC 中拥有2 functions,例如page1.htmpage2.htm,并且只有1 个控制器,有点在CodeIgniter 中,我不知道为什么这么难...

这就是我到现在为止所做的

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

// Import models
import models.LoginModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Candy
 */

@RequestMapping("/app")
public class LoginController extends SimpleFormController {
    public LoginController()
    {
        //Initialize controller properties here or 
        //in the Web Application Context

        setCommandClass(models.Employee.class);
        setCommandName("Employee");
        //setSuccessView("pages/login/login_form_view");
        //setFormView("pages/login/login_execute_view");
    }


    // On form load
    @Override
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception 
    {
        LoginModel loginModel = new LoginModel(request);

        if(!loginModel.isLogged())
        {
            ModelAndView mv = new ModelAndView("pages/login/login_form_view");

            // mv.addObject("chestie",loginModel.isLogged());

            return mv;
        }
        else
        {
            return new ModelAndView("redirect:/dashboard.htm");
        }


    }

    @Override
    protected void doSubmitAction(Object command) throws Exception
    {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    @Override
    protected ModelAndView onSubmit(
    HttpServletRequest request, 
    HttpServletResponse response, 
    Object command, 
    BindException errors) throws Exception 
    {
        // User has submited a POST request
        ModelAndView mv = new ModelAndView("pages/login/login_execute_view");

        // Check if the user is logged or not, user must be NOT LOGGED in order to log
        LoginModel loginModel = new LoginModel(request);
        if(!loginModel.isLogged())
        {
            // Just continue
            String email = request.getParameter("email").toString();
            String password = request.getParameter("password").toString();

            // Check this email/pass
            Map<String,String> resultLogin = loginModel.login(email, password);

            String result = resultLogin.get("result").toString();
            String reason = resultLogin.get("reason").toString();
            // String qqq = resultLogin.get("qqq").toString();

            /*
            java.util.Date dt = new java.util.Date();

            java.text.SimpleDateFormat sdf = 
                 new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String currentTime = sdf.format(dt);
            */
            if(result == "true")
            {
                // Login is good, redirect to dashboard
                return new ModelAndView("redirect:/dashboard.htm");

                // Display the error
                //mv.addObject("loginResult",result);
                //mv.addObject("loginReason",reason);
                //mv.addObject("qqq",qqq);
                //mv.addObject("qqq2",request.getSession().getAttribute("is_logged").toString());
            }
            else
            {
                // Display the error
                mv.addObject("loginResult",result);
                mv.addObject("loginReason",reason);

                return mv;
            }

        }
        else
        {
            return new ModelAndView("redirect:/login.htm");
        }
    }     
}

如果我删除此控制器将无法工作

applicationContext.xml
<bean class="controllers.LoginController"/>

dispatcher-servlet.xml
<bean class="controllers.LoginController" p:formView="pages/login/login_form_view" p:successView="pages/login/login_execute_view"/>

web.xml
<servlet>
    <servlet-name>LoginController</servlet-name>
    <servlet-class>controllers.LoginController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginController</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
  1. 为什么在创建新控制器时必须编辑 3 个 XML?是不是更简单的方法?

  2. 我现在只想创建另一个函数logout() 来加载ModelAndView mv = new ModelAndView("pages/login/logout_view");,仅此而已。

还有这个

@RequestMapping("/app")
@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception 
{
    ModelAndView mv = new ModelAndView("pages/login/login_form_view");

    return mv;
}

给我 404 错误...

  1. 我应该使用什么? SimpleFormControllerextend ControllerAbstractController(我正在使用NETBEANS)。我很困惑,我希望有一个像CodeIgniter 这样的好的java 框架。我不太了解映射的工作原理,但我知道 apache rewrite 的工作原理。

非常感谢。

【问题讨论】:

  • 你已经有了 Spring 3.0,所以考虑使用基于注解的 @Controller 控制器。
  • 你能举个例子吗?像链接/视频?我对这个框架感到困惑....
  • 那里有很多资源。看看就好。
  • 还有result == "true" -> 不要那样做。
  • @Rohit Jain => 我痴迷于来自 PHP 的关联数组,例如 if($result_function['result'] == 'true') then ... do stuff ...这就是为什么 ... @SotiriosDelimanolis 相信我,我已经搜索过了,它不像 PHPASP 一切似乎都合乎逻辑和清晰,我被困在基本的事情上……相信我,我以前使用过网络技术……

标签: java spring jakarta-ee spring-mvc spring-security


【解决方案1】:

如果您使用的是 Spring 3,您可以轻松地将 @controller 注释用于您的控制器类,用于您的页面请求和导航。

您可以将@Service 注释用于您的业务逻辑,将@Repository 用于您的数据库事务,并使用@Autowired 注释将这些层绑定在一起。

所以你的请求是这样的(UI Request -> @Controller -> @Service -> @Repository)并再次返回原始控制器类进行导航。

但是关于您的问题,当您在 spring 中使用 @Controller 注释标记一个类时,这仅仅意味着您为 URL 映射和导航候选该类,下面的示例显示了如何在 Controller 类中使用 @RequestMapping 注释用于您的 URL 映射:

@Controller
@RequestMapping("/employee")
public class Employees{

@AutoWired
private EmployeeServiceInterface empServInt;

  @ModelAttribute("empAdd")
  public Employee createEmployeeModel(){
      return new Employee();
  } 

  @RequestMapping(value="/add", method = RequestMethod.POST)
  public String addEmployee(@ModelAttribute("empAdd")Employee employee,Model model, HttpSesion session){

     Employee employee = empServInt.createUser(employee);
     if(yourCondition()){
          return "redirect:/TO_THIS_PAGE";
      }
    return "GO_TO_PAGE_NAVIGATION_HERE";
  }
}

请注意,@RequestMapping 在带有 URL HOST_NAME:PORT/PROJECT_NAME/employee/add 的请求时被激活,因为 @RequesMapping 注释值。

其次,@ModelAttribute 您在示例中看到为您的页面创建一个模型,该模型可帮助您使用 Spring Form 标签中的 commandName 属性从 UI 提交 Employee Object Bean 值,该标签使用 path="" 将 html 输入绑定到 Employee Bean 类属性:

<form:form commandName="empAdd" method="post" >...</form:form>

第三,注意@AutoWired 可以自动将接口连接到实现,因此在我的示例中,如果像 EmployeeServiceImpl 这样的类通过调用接口方法来实现接口EmployeeServiceInterfaceempServInt.createUser(employee); spring 会自动调用相关的 EmployeeServiceImpl.createUser (员工)为您提供的实施方法。

第四:请注意,为了能够使用 Controller 和 Service & Repository 注释工作,您应该在 Spring Descriptor XML 文件中定义具有这些注释的包,如下所示:

<context:component-scan base-package="java.package" />

第五,如果您注意到Employees 中的方法具有提供导航的String 返回类型,但要使其正常工作,您应该定义将在Spring Descriptor XMl 文件中返回的页面前缀和后缀,如下所示:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

根据上面的配置,如果你使用@RequestMapping注解的方法返回了employeeString,Spring去从这个位置获取页面:

[PREFIX]employee[POSSIX] --> /WEB-INF/view/employee.jsp

为了更好地理解,我为您找到了一个有用的示例链接。 Link

祝你好运!

【讨论】:

  • 非常感谢,但不是我看不懂,而是java web对我来说很奇怪,你能看看我的项目吗?我被困住了,拜托。我在 NETBEANS 中做到了。正如你所看到的,我尝试了,但没有尝试,甚至没有简单的页面 ==>> wetransfer.com/downloads/… 非常感谢!
猜你喜欢
  • 2010-12-15
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2012-11-08
相关资源
最近更新 更多