1. 程式人生 > >Eclipse下用maven構建Struts專案,實現簡單的登入及驗證。

Eclipse下用maven構建Struts專案,實現簡單的登入及驗證。

點選File->new->Maven Project.

右鍵所建立的專案->點選Properties->點選Java Build Path將JDK改成所需要的版本

然後點選Project Facets先改Java,再改Dynamic Web Module。否則Dynamic Web Module不能改

最後點選Deployment Assembly對應好路徑。將src/main下的webapp檔案刪除。右鍵專案Java EE Tools 生成一個新的web.xml

在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.qst</groupId>     <artifactId>Struts2Demo</artifactId>     <packaging>war</packaging>     <version>0.0.1-SNAPSHOT</version>     <name>Struts2Demo Maven Webapp</name>     <url>http://maven.apache.org</url>     <dependencies>         <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->         <dependency>             <groupId>org.apache.struts</groupId>             <artifactId>struts2-core</artifactId>             <version>2.3.32</version>         </dependency>         <!-- https://mvnrepository.com/artifact/org.apache.struts.xwork/xwork-core -->         <dependency>             <groupId>org.apache.struts.xwork</groupId>             <artifactId>xwork-core</artifactId>             <version>2.3.32</version>         </dependency>         <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->         <dependency>             <groupId>commons-logging</groupId>             <artifactId>commons-logging</artifactId>             <version>1.2</version>         </dependency>         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>3.1.0</version>             <scope>provided</scope>         </dependency>         <dependency>             <groupId>junit</groupId>             <artifactId>junit</artifactId>             <version>4.0</version>             <scope>test</scope>         </dependency>     </dependencies>     <build>         <finalName>Struts2Demo</finalName>     </build> </project>

右鍵專案。點選Maven然後update maven-----------------------------等待Jar包下載完成

在src/main/resources下新建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.i18n.encoding" value="UTF-8"></constant>     <constant name="struts.devMode" value="true"></constant>          <include file="struts-product.xml"></include>          <package name="user" namespace="/user" extends="struts-default">              <global-results>             <result name="error">/error.jsp</result>         </global-results>         <global-exception-mappings>             <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>         </global-exception-mappings>                  <action name="userAction_*" method="{1}" class="com.qst.action.UserAction">             <result name="main" type="dispatcher">/main.jsp</result>             <result name="login" type="dispatcher">/login.jsp</result>             <result name="input">/login.jsp</result>         </action>         <!-- <action name="*_*" method="{2}" class="com.qst.action.{1}">             <result name="main" type="redirect">/main.jsp</result>             <result name="login" type="dispatcher">/login.jsp</result>         </action> -->         <!-- <action name="userActionlist" method="list" class="com.qst.action.UserAction">             <result name="main" type="redirect">/main.jsp</result>             <result name="login" type="dispatcher">/login.jsp</result>         </action> -->     </package> </struts>

在web.xml中配置:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 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>Struts2Demo</display-name>   <filter>       <filter-name>Struts2Filter</filter-name>       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>   </filter>   <filter-mapping>       <filter-name>Struts2Filter</filter-name>       <url-pattern>/*</url-pattern>   </filter-mapping>   <welcome-file-list>     <welcome-file>index.html</welcome-file>     <welcome-file>index.htm</welcome-file>     <welcome-file>index.jsp</welcome-file>     <welcome-file>default.html</welcome-file>     <welcome-file>default.htm</welcome-file>     <welcome-file>default.jsp</welcome-file>   </welcome-file-list> </web-app>

main.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:debug/> 歡迎您:${sessionScope.username} <br>${applicationScope.appname } <br>${requestScope.requestarg } </body> </html>

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  pageContext.setAttribute("basePath",basePath);  %>  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> <base href="${pageScope.basePath}"> <script type="text/javascript"> function validate(){     if($("#username").val()=="" || $("#userpass").val()==""){         alert("使用者名稱或密碼不能為空!");         return false;     }else if($("#userpass").val().length<6 || $("#userpass").val().length>12){         alert("密碼長度範圍6-12");         return false;     }     return true; } </script> </head> <body> <s:debug/> <s:fielderror cssStyle="color:red"></s:fielderror> <p><font color=red>${error}${requestScope.action.fieldErrors["user.username"]}</font></p> <form action="user/userAction_login" method="post"> <p>username:<input name="user.username" id="username" type="text"/></p> <p>userpass:<input name="user.userpass" id="userpass" type="password"/></p> <p><input type="submit" value="提交"/></p> </form> </body> </html>

error.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> error! ${exception} </body> </html>

Users:

package com.qst.po;

public class Users {

    private String username;          private String userpass;          public Users() {              }          public Users(String username,String userpass) {         this.username=username;         this.userpass=userpass;     }

    public String getUsername() {         return username;     }

    public void setUsername(String username) {         this.username = username;     }

    public String getUserpass() {         return userpass;     }

    public void setUserpass(String userpass) {         this.userpass = userpass;     }           } UserDao.java:

package com.qst.dao;

import com.qst.po.Users;

public interface UserDao {

    public Users selectLogin(Users user); }

UserDaoImpl.java:

package com.qst.dao;

import com.qst.po.Users;

public class UserDaoImpl implements UserDao {

         @Override     public Users selectLogin(Users user) {         String sql="select * from tb_users where username=? and userpass=?";         if("張三".equals(user.getUsername()) && "123456".equals(user.getUserpass()))             return user;         return null;     }

} UserService.java

package com.qst.service;

import com.qst.po.Users;

public interface UserService {

    public boolean login(Users user); } UserServiceImpl.java:

package com.qst.service;

import com.qst.dao.UserDao; import com.qst.dao.UserDaoImpl; import com.qst.po.Users;

public class UserServiceImpl implements UserService {

    UserDao userDao = new UserDaoImpl();          @Override     public boolean login(Users user) {         Users u = userDao.selectLogin(user);         if(u==null)             return false;         return true;     }

}

UserAction.java:

package com.qst.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.qst.po.Users; import com.qst.service.UserService; import com.qst.service.UserServiceImpl;

public class UserAction extends ActionSupport{

    Users user;     String error;          public String register() {         return "";     }          public String list() {         return "";     }          public String login() {         UserService userService = new UserServiceImpl();         boolean login = userService.login(user);         if (login) {             Map<String,Object> session = ActionContext.getContext().getSession();             session.put("username", user.getUsername());                          Map<String,Object> application = ActionContext.getContext().getApplication();             application.put("appname", "struts2app");                          ActionContext.getContext().put("requestarg", "requestarg");                          return "main";         } else {             error = "密碼在六到十六位";             return "login";         }     }          public void validateLogin() {         if("".equals(user.getUsername())) {             super.addFieldError("user.username", "請輸入正確的使用者名稱");         }         if(user.getUserpass().length()<6 || user.getUserpass().length()>12) {             super.addFieldError("user.userpass", "    請輸入正確的密碼");         }     }

    @Override     public void validate() {         System.out.println("validate()");     }

    public Users getUser() {         return user;     }

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

    public String getError() {         return error;     }          

}